PHP ARRAYS AND
SUPERGLOBALS
Php Arrays
An array is a data structure that stores an arbitrary number of values in a single value. An array in PHP is actually
an ordered map, where map is a type that associates values to keys.
Syntax
• $array = array('Value1', 'Value2', 'Value3'); // Keys default to 0, 1, 2, ...,
• $array = array('Value1', 'Value2', ); // Optional trailing comma
• $array = array('key1' => 'Value1', 'key2' => 'Value2', ); // Explicit keys
• $array[] = 'ValueX'; // Append 'ValueX' to the end of the array
2
Sameeha Moogab
Initializing an Array
An array can be initialized empty:
// An empty array
$foo = array();
// Shorthand notation available
since PHP 5.4
$foo = [];
An array can be initialized and preset with values:
// Creates a simple array with
three strings
$fruit = array('apples',
'pears', 'oranges’);
$fruit
// A simple = array
associative
array(
'first' =>
'apples',
'second' =>
'pears',
'third' => 3
'oranges'
Sameeha Moogab
);
Functions
Syntax
• function func_name($parameterName1, $parameterName2) { code_to_run(); }
• function func_name($optionalParameter = default_value) { code_to_run(); }
• function func_name(type_name $parameterName) { code_to_run(); }
• function func_name(&$referenceParameter) { code_to_run(); }
function hello($name, $style =
'Formal')
{ function pluralize(&$word)
switch ($style) { {
case 'Formal': if (substr($word, -1) ==
print "Good Day $name";
'y') {
break;
case 'Informal': $word = substr($word, 0, -1)
print "Hi $name"; . 'ies';
break; } else {
case 'Australian':
print "G'day $name"; $word .= 's';
break; }
default: }
print "Hello $name";
break;
$word = 'Bannana';
pluralize($word);
}
} print $word; // Bannanas 4
hello('Alice’); // Good Day Alice
Sameeha Moogab
Functions
range ( mixed $start , mixed $end, [ number $step = 1 ] )
the range() function creates an array containing a range of elements. The first two parameters are required,
where they set the start and end points of the (inclusive) range. The third parameter is optional and defines the
size of the steps being taken. Creating a range from 0 to 4 with a stepsize of 1, the resulting array would consist
of the following elements: 0, 1, 2, 3, and 4. If the step size is increased to 2 (i.e. range(0, 4, 2)) then the resulting
array would be: 0, 2, and 4.
$array = [];
$array_with_range = range(3, 6);
for ($i = 1; $i <= 4; $i++) {
$array[] = $i;
}
print_r($array); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4
)
print_r($array_with_range); // Array ( [0] => 3 [1] => 4 [2] =>
5
5 [3]
Sameeha Moogab => 6 )
• Use array_key_exists() or isset() or !empty() • The function in_array() returns true if an item exists in an
array
$map = [ $fruits = ['banana',
'foo' => 1, 'apple'];
'bar' => null, $foo = in_array('banana',
'foobar' => ‘ ', $fruits);
]; // $foo value is true
array_key_exists('foo', $map); $bar = in_array('orange',
// true $fruits);
isset($map['foo']); // true // $bar value is false
!empty($map['foo']); // true
array_key_exists('bar', $map);
// true
isset($map['bar']); // false
!empty($map['bar']); // false
6
Sameeha Moogab
Functions
You can also use the function array_search() to get the key of a specific item in an array.
$userdb = [
[
"uid" => '100',
"name" => 'Sandra Shush',
"url" => 'urlof100',
],
[
"uid" => '5465',
"name" => 'Stefanie Mcmohn',
"pic_square" => 'urlof100',
],
[
"uid" => '40489',
"name" => 'Michael',
"pic_square" => 'urlof40489',
]
];
$key = array_search(40489, array_column($userdb, 'uid'));
echo $key; 7
Sameeha Moogab
Sorting an Array
sort()
Sort an array in ascending order by value. Array
$fruits = ['Zitrone', 'Orange', (
[0] => Apfel
'Banane', 'Apfel']; [1] => Banane
sort($fruits); [2] => Orange
[3] => Zitrone)
print_r($fruits);
rsort()
Sort an array in descending order by value.
$fruits = ['Zitrone', 'Orange',
Array
'Banane', 'Apfel']; (
rsort($fruits); [0] => Zitrone
[1] => Orange
print_r($fruits); [2] => Banane
asort() [3] => Apfel)
Sort an array in ascending order by value and preserve the
indecies.
arsort()
Sort an array in descending order by value and preserve the
indecies.
ksort() / krsort() Array
Sort an array in ascending order by key and krsort in descending order by (
[a] => orange
key [b] => banana
$fruits = ['d'=>'lemon', 'a'=>'orange',
'b'=>'banana', 'c'=>'apple'];
[c] => apple
[d] => lemon) 8
Sameeha Moogab
ksort($fruits);
print_r($fruits);
Merge two arrays into one array
$a1 = array("red","green");
$a2 = array("blue","yellow");
print_r(array_merge($a1,$a2));
/*
Array ( [0] => red [1] => green [2] => blue [3] =>
yellow )
*/
Associative array:
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
/*
Array ( [a] => red [b] => yellow [c] => blue )
*/
1.Merges the elements of one or more arrays together so that the values of one are appended to the end of the
previous one. It returns the resulting array.
2.If the input arrays have the same string keys, then the later value for that key will overwrite
the previous one. If, however, the arrays contain numeric keys, the later value will not
overwrite the original value, but will be appended.
3.Values in the input array with numeric keys will be renumbered with incrementing keys 9
starting from zero in the result array.
array_reduce
array_reduce reduces array into a single value. Basically, The array_reduce will
go through every
item with the result from last iteration and produce new value to the next
iteration.
Usage: array_reduce ($array, function($carry, $item){...}, $defaul_value_of_first_carry)
Sum of array
$result = array_reduce([1, 2, 3, 4, 5],
function($carry, $item){
return $carry + $item; result:15
});
The largest number in array
$result = array_reduce([10, 23, 211, 34, 25],
function($carry, $item){
result:211
return $item > $carry ? $item : $carry;
});
Like implode($array, $piece)
$result = array_reduce(["hello", "world", "PHP",
"language"], function($carry, $item){ result:"hello-world-PHP-
return !$carry ? $item : $carry . "-" . $item ; language"
});
10
Sameeha Moogab
The function date() takes one parameters - a format, which is a string
$date = new DateTime('2000-05-26T13:30:20'); /*
Friday, May 26, 2000 at 1:30:20 PM */
$date->format("H:i");
/* Returns 13:30 */
$date->format("H i s");
/* Returns 13 30 20 */
$date->format("h:i:s A");
/* Returns 01:30:20 PM */
$date->format("j/m/Y");
/* Returns 26/05/2000 */
$date->format("D, M j 'y - h:i A");
/* Returns Fri, May 26 '00 - 01:30
11
Sameeha Moogab
• RandomNumbers
<?php
$array = [];
function randomNumbers(int $length)
{
$array = [];
for ($i = 0; $i < $length; $i++) {
$array[] = mt_rand(1, 10);
}
return $array;
}
$random = randomNumbers(10);
print_r ($random);
?>
12
Sameeha Moogab
PHP superglobal
Superglobals are built-in variables that are always available in all scopes.
The PHP superglobal variables are :
$GLOBALS
$_SERVER
$_GET
$_POST
$_FILES
$_COOKIE
$_SESSION
13
Sameeha Moogab
PHP superglobal
$_SERVER is a PHP super global variable which holds information about headers, paths,
and script locations.
$_SERVER['PHP_SELF’];
$_SERVER['SERVER_NAME'];
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
$GLOBALS is a PHP super global variable which is used to access global variables from
anywhere in the PHP script (also from within functions or methods).
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z; 14
Sameeha Moogab
?>
PHP superglobal
$_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with
method="post". $_POST is also widely used to pass variables.
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}}
?>
15
Sameeha Moogab
PHP superglobal
PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form
with method="get
<a href="edit.php?id=<?= $person->id ?>" class="btn btn-info">Edit</a>
-----------------------------------------------------------------------
$id = $_GET['id'];
$sql = 'DELETE FROM users WHERE id=:id';
$_COOKIE - An associative array of variables passed to the current script via HTTP Cookies
$_COOKIE['shopping_cart']
$_SESSION - An associative array containing session variables available to the current script.
$_SESSION['id']=$user->id;
$_FILES - An associative array of items uploaded to the current script via the HTTP POST method.
$tmp_name = $_FILES['image']['tmp_name']; 16
Sameeha Moogab