php, Arrays

March 12, 2012
By

Array keys start from 0, not 1.
In an associative array a key is associated with a value.
An array in PHP is actually an ordered map. (each key is mapped to a value).
array values can be other arrays, trees and multidimensional arrays are also possible.
A value can be any PHP type.
A key may be either an integer or a string. Floats in keys are truncated to integer.
“8″ will be interpreted as 8, while “08″ will be interpreted as “08″
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

$array = array(1, 2, 3, 4, 5, 8 => 8, 7 => 7, 19, 6 => 13);

print_r ($array);

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [8] => 8
[7] => 7 [9] => 19 [6] => 13 )

This example creates a 1-based (not 0) index array.

$firstquarter = array(1 => ‘January’, ‘February’, ‘March’);
print_r($firstquarter);

Array ( [1] => January [2] => February [3] => March )

sort($array); rsort($array); #(reverse sort)

unset($arr); // clears the entire array
unset($arr[x]); // This removes the element from the array

The unset($arr[x]) function removes the key (and its value) from an array. Be aware that the array will not be reindexed.

How to reindex an array

the array can be reindexed this way:
example: index starting with 1:

 $keynew = 1 ;  
 $arraynew = array(); 
 foreach ( $arrayold as $key => $val )
    {
    $arraynew[ $keynew ] = $val;
    $keynew++ ; 
    }

// delete every item, but leave the array itself intact:
foreach ($array as $i => $value)
{ unset($array[$i]); }

to empty an array

unset($arr); // This deletes the whole array

$Array = array(); // this creates an empty array

 

convert an object (collection) to an array

to convert a 1 dimentional collection of objects to an array:

// cast the object
$array = (array)$obj;

to convert a multi-dimentional collection of objects to an array:

$array=array();
foreach($object as $member=>$data)
{ $array[$member]=$data; }

enhanced version

function objectToArray($object)
{ if(!is_object($object) && !is_array($object)) return $object;
$array=array();
foreach($object as $member=>$data)
{ $array[$member]=objectToArray($data); }
return $array;
}

$object = get_object_vars( $object );
array_map( ‘objectToArray’, $object );

 

You may have noticed that the following are functionally identical:

while (list(, $value) = each ($arr))
{ echo “Value: $value <br>\n”; }

foreach ($arr as $value)
{ echo “Value: $value <br>\n”; }

The following are also functionally identical:

reset($arr);
while (list($associativeKey, $value) = each ($arr))
{ echo “Key: $associativeKey; Value: $value <br>”; }

foreach ($arr as $key => $value)
{ echo “Key: $key; Value: $value <br>”; }

foreach ($_POST AS $key=>$value) echo ‘ <br> key:’.$key.’ value:’.$value ;

for($i=0;$iuserkey == $dspUser[$i+1]->userkey )
{ $userstests .= ‘ ‘.$dspUser[$i]->testkey.’ ‘ ; }
else
{ // display user record … }

$queue = array(“orange”, “banana”);
array_unshift($queue, “apple”, “raspberry”);

This would result in $queue having the following elements:
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)

See also array_shift(), array_push(), and array_pop().

// add an element to the end
array_push($queue, ‘strawberry’);

// remove an element from the end
array_pop($queue);

For each element of the $employeeAges associative array:

The operator “=>” represents the relationship between a key and value. You can
imagine that the key points => to the value. In our example we name the key
$name and the value $age.

PHP Code:
————————————–
$employeeAges["Lisa"] = “28″;
$employeeAges["Jack"] = “16″;
$employeeAges["Ryan"] = “35″;
$employeeAges["Rachel"] = “46″;
$employeeAges["Grace"] = “34″;

foreach( $employeeAges as $name => $age )
{ echo “Name: $name, Age: $age <br>”; }

————————————–
Display:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34
————————–

Some more examples to demonstrate usages:

/* foreach example 1: value only */

$a = array (1, 2, 3, 17);

foreach ($a as $v) {
echo “Current value of \$a: $v.\n”;
}

/* foreach example 2: value (with key printed for illustration) */

$a = array (1, 2, 3, 17);
$i = 0; /* for illustrative purposes only */
foreach ($a as $v)
{
echo “\$a[$i] => $v.\n”;
$i++;
}

/* foreach example 3: key and value */

$a = array (
“one” => 1,
“two” => 2,
“three” => 3,
“seventeen” => 17
);

foreach ($a as $k => $v) {
echo “\$a[$k] => $v.\n”;
}

/* foreach example 4: multi-dimensional arrays */

$a[0][0] = “a”;
$a[0][1] = “b”;
$a[1][0] = “y”;
$a[1][1] = “z”;

 foreach ($a as $v1) 
    { foreach ($v1 as $v2) 
        {  echo "$v2\n";  }
    }

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v)
{ echo “$v\n”; }

Leave a Reply

Your email address will not be published. Required fields are marked. *
Comments will be approved as soon as possible.