Page 159 - Open Soource Technologies 304.indd
P. 159
Unit 7: Multidimensional Arrays
$nums = range(1, 7); $rows = array_chunk($nums, 3); print_r($rows); Array ( [0] => Array ( Notes
[0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [2] => Array ( [0] => 7 ) )
7.2.3 Keys and Values
The array_keys( ) function returns an array consisting of only the keys in the array, in internal
order:
$array_of_keys = array_keys(array);
Here’s an example:
$person = array(‘name’ => ‘Pradip’, ‘age’ => 35, ‘wife’ => ‘Riya’); $keys = array_keys($person);
// $keys is array(‘name’, ‘age’, ‘wife’)
PHP also provides a (less generally useful) function to retrieve an array of just the values in an
array, array_values( ) :
$array_of_values = array_values(array);
As with array_keys( ), the values are returned in the array’s internal order:
$values = array_values($person); // $values is array(‘Pradip’, 35, ‘Riya’);
7.2.4 Checking whether an Element Exists
To see if an element exists in the array, use the array_key_exists( ) function:
if (array_key_exists(key, array)) { ... }
The function returns a Boolean value that indicates whether the second argument is a valid key
in the array given as the first argument.
It’s not sufficient to simply say:
if ($person[‘name’]) { ... } // this can be misleading
Even if there is an element in the array with the key name, its corresponding value might be
false (i.e., 0, NULL, or the empty string). Instead, use array_key_exists( ) as follows:
$person[‘age’] = 0; // unborn? if ($person[‘age’]) { echo “true!\n”; } if (array_key_exists(‘age’,
$person)) { echo “exists!\n”; } exists!
In PHP 4.0.6 and earlier versions, the array_key_exists( ) function was called key_exists( ). The
original name is still retained as an alias for the new name.
Many people use the isset( ) function instead, which returns true if the element exists and is
not NULL:
$a = array(0,NULL,’’);
function tf($v)
{
return $v ? “T” : “F”;
}
for ($i=0; $i < 4; $i++)
{
printf(“%d: %s %s\n”, $i, tf(isset($a[$i])), tf(array_key_exists($i, $a)));
}
LOVELY PROFESSIONAL UNIVERSITY 153