If you are looking to assign the values of an array to a group of variables with one statement, use list(). This construct is used to give a list of variables some value. They work only with arrays that use numeric indexes.
Example:
<?php $names = array ("Ashish", "Michael", "Chris"); list($name1, $name2, $name3) = $names; echo $name1; echo "<br />"; echo $name2; echo "<br />"; echo $name3; ?>
Output: Ashish Chris Michael
You can also use list to pick individual values while skipping the ones that you do not want.
Example:
<?php $names = array ("Ashish", "Michael", "Chris"); list( , ,$name1) = $names; echo $name1; ?>
Output: Chris
Multi Dimensional Arrays
As long as the array is an indexed array, you can use lists to access the values of arrays that go multi levels deep. All you have to do is nest the list() construct as well.
Example:
<?php $names=array( array("Ashish",27), array("Michael",20), array("Chris",35) ); list(list($name1,$age1),list($name2,$age2),list($name3,$age3))=$names; echo $name1 ." - ". $age1; echo "<br />"; echo $name2 ." - ". $age2; echo "<br />"; echo $name3 ." - ". $age3; ?>
Output: Ashish - 27 Michael - 20 Chris - 35
Using Each and List Together to Access Arrays
The list() construct is also used together with each() php function to access the values of an array. The each() statement retrieves the key and value of the current array position. We can loop it access all the keys and arrays.
Example:
<?php $names = array ("Ashish", "Michael", "Chris"); while (list($key, $val) = each($names)) { echo "$key => $valn"; echo "<br />"; } ?>
Output: 0 => Ashish 1 => Michael 2 => Chris