- PHP foreach with Nested Array? [duplicate]
- 5 Answers 5
- Php foreach array with arrays
- Unpacking nested arrays with list()
- PHP — Foreach (Array of an Array)
- 5 Answers 5
- Two arrays in foreach loop
- 24 Answers 24
- All fully tested
- 3 ways to create a dynamic dropdown from an array.
- Method #1 (Normal Array)
- Method #2 (Normal Array)
- Method #3 (Associative Array)
PHP foreach with Nested Array? [duplicate]
I have a nested array in which I want to display a subset of results. For example, on the array below I want to loop through all the values in nested array[1].
Array ( [0] => Array ( [0] => one [1] => Array ( [0] => 1 [1] => 2 [2] => 3 ) ) [1] => Array ( [0] => two [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) ) [2] => Array ( [0] => three [1] => Array ( [0] => 7 [1] => 8 [2] => 9 ) ) )
I was trying to use the foreach function but I cannot seem to get this to work. This was my original syntax (though I realise it is wrong).
$tmpArray = array(array(«one»,array(1,2,3)),array(«two»,array(4,5,6)),array(«three»,array(7,8,9))); foreach ($tmpArray[1] as $value)
I was trying to avoid a variable compare on whether the key is the same as the key I want to search, i.e.
foreach ($tmpArray as $key => $value) < if ($key == 1) < echo $value; >>
Your intial syntax seems ok, but $value can be an array itself in the foreach . In that case you can’t just echo it but you need to loop through it too.
Your minimal reproducible example isn’t crystal clear. Maybe you want to destructure your array data with the foreach() ? 3v4l.org/TN52M
5 Answers 5
If you know the number of levels in nested arrays you can simply do nested loops. Like so:
// Scan through outer loop foreach ($tmpArray as $innerArray) < // Check type if (is_array($innerArray))< // Scan through inner loop foreach ($innerArray as $value) < echo $value; >>else < // one, two, three echo $innerArray; >>
if you do not know the depth of array you need to use recursion. See example below:
// Multi-dementional Source Array $tmpArray = array( array("one", array(1, 2, 3)), array("two", array(4, 5, 6)), array("three", array( 7, 8, array("four", 9, 10) )) ); // Output array displayArrayRecursively($tmpArray); /** * Recursive function to display members of array with indentation * * @param array $arr Array to process * @param string $indent indentation string */ function displayArrayRecursively($arr, $indent='') < if ($arr) < foreach ($arr as $value) < if (is_array($value)) < // displayArrayRecursively($value, $indent . '--'); >else < // Output echo "$indent $value \n"; >> > >
The code below with display only nested array with values for your specific case (3rd level only)
$tmpArray = array( array("one", array(1, 2, 3)), array("two", array(4, 5, 6)), array("three", array(7, 8, 9)) ); // Scan through outer loop foreach ($tmpArray as $inner) < // Check type if (is_array($inner)) < // Scan through inner loop foreach ($inner[1] as $value) < echo "$value \n"; >> >
Php foreach array with arrays
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (iterable_expression as $value) statement foreach (iterable_expression as $key => $value) statement
The first form traverses the iterable given by iterable_expression . On each iteration, the value of the current element is assigned to $value .
The second form will additionally assign the current element’s key to the $key variable on each iteration.
Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key() .
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
$arr = array( 1 , 2 , 3 , 4 );
foreach ( $arr as & $value ) $value = $value * 2 ;
>
// $arr is now array(2, 4, 6, 8)
unset( $value ); // break the reference with the last element
?>?php
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset() . Otherwise you will experience the following behavior:
// without an unset($value), $value is still a reference to the last item: $arr[3]
foreach ( $arr as $key => $value ) // $arr[3] will be updated with each value from $arr.
echo » < $key >=> < $value >» ;
print_r ( $arr );
>
// . until ultimately the second-to-last value is copied onto the last value
// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>
It is possible to iterate a constant array’s value by reference:
Note:
foreach does not support the ability to suppress error messages using @ .
Some more examples to demonstrate usage:
/* foreach example 1: value only */
?php
foreach ( $a as $v ) echo «Current value of \$a: $v .\n» ;
>
/* foreach example 2: value (with its manual access notation printed for illustration) */
$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 = array();
$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» ;
>
?>
Unpacking nested arrays with list()
It is possible to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.
foreach ( $array as list( $a , $b )) // $a contains the first element of the nested array,
// and $b contains the second element.
echo «A: $a ; B: $b \n» ;
>
?>
The above example will output:
You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:
foreach ( $array as list( $a )) // Note that there is no $b here.
echo » $a \n» ;
>
?>
The above example will output:
A notice will be generated if there aren’t enough array elements to fill the list() :
foreach ( $array as list( $a , $b , $c )) echo «A: $a ; B: $b ; C: $c \n» ;
>
?>
The above example will output:
Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C:
PHP — Foreach (Array of an Array)
I forgot to mention: This script works fine on both my servers. But, When I include array_unique before «Foreach» is called, it doesn’t work, no error message or anything.
The output on my local server prints out a unique list of names and a unique list of items they viewed.
5 Answers 5
$name = "Phill"; $email = "me@me.com"; $password = "p@ssw0rd"; for($i=1; $i < 10; $i++)< $marray[] = array($name, $email, $password); >foreach (array_unique($marray) as $e)< echo "Name: ". $e[0]."
"; echo "Email: ". $e[1]."
"; >
What version of PHP are you using?
I would check which version of PHP both servers have installed. you can do this with phpinfo(). I can’t think of any other reason it would work on one server, but not another. What do you mean by ‘doesn’t recognize?’ do you get any error messages? If so, what are they?
Actually I forgot to mention. That script up there works fine. When I use «array_unique», that’s when it fails. I don’t get any error message, It just «foreachs» one record instead of the example up there «10 records».
Here is a cut out: $q = mysql_query($strSQL); $hold = array(); $view = array(); while($rez = mysql_fetch_array($q)) < $view[] = array($rez[6],$rez[1],$rez[8],$rez[9]); $hold[] = array($rez[2],$rez[3],$rez[6]); >$hold = array_unique($hold); sort($hold); $view = array_unique($view); sort($view); foreach($hold as $u) < echo $u[0]; >
array_unique casts whatever is in the array (in this case, another array) as a string. it’s not really designed to work with arrays of arrays, you may want to write your own custom function. Also, it’s possible that there is some difference in the mySQL data that is causing the problem.
Two arrays in foreach loop
I want to generate a selectbox using two arrays, one containing the country codes and another containing the country names. This is an example:
24 Answers 24
foreach( $codes as $code and $names as $name )
You probably want something like this.
foreach( $codes as $index => $code ) < echo ''; >
Alternatively, it’d be much easier to make the codes the key of your $names array.
$names = array( 'tn' => 'Tunisia', 'us' => 'United States', . );
avoid starting your answer with non-functional code only to say later that it doesn’t work. A negative statement should be prefaced as negative when it spans multiple paragraphs
foreach operates on only one array at a time.
The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:
foreach (array_combine($codes, $names) as $code => $name) < echo ''; >
Or as seen in the other answers, you can hardcode an associative array instead.
@xjshiya No, if you give them 3 parameters you get Warning: array_combine() expects exactly 2 parameters, 3 given
Use array_combine() to fuse the arrays together and iterate over the result.
$countries = array_combine($codes, $names);
$codes = array('tn','us','fr'); $names = array('Tunisia','United States','France'); array_map(function ($code, $name) < echo ''; >, $codes, $names);
- If one array is shorter than the other, the callback receive null values to fill in the gap.
- You can use more than 2 arrays to iterate through.
array_map() is appropriate when its return value is accessed. When the return data is unneeded, array_walk() is more appropriate.
Hi, true for the return functionality, though array_walk() doesn’t accept more than one array (to iterate on each element of the 2 arrays at the same time), you may use its 3rd argument $arg , but you will get the whole array in each iteration instead of each of its elements.
$code_names = array( 'tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France'); foreach($code_names as $code => $name) < //. >
I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.
+1 array_combine() already produces an associative array, you may want to be clearer about initializing it as associative.
$codes = array('tn', 'us', 'fr'); $names = array('Tunisia', 'United States', 'France'); foreach($codes as $key => $value) < echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "
"; >
Your code like this is incorrect as foreach only for single array:
Alternative, Change to this:
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:
$codes = array('tn','us','fr'); $names = array('Tunisia','United States','France');
$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
You can use array_merge to combine two arrays and then iterate over them.
$array1 = array("foo" => "bar"); $array2 = array("hello" => "world"); $both_arrays = array_merge((array)$array1, (array)$array2); print_r($both_arrays);
All fully tested
3 ways to create a dynamic dropdown from an array.
This will create a dropdown menu from an array and automatically assign its respective value.
Method #1 (Normal Array)
'Tunisia','us'=>'United States','fr'=>'France'); echo ''; ?>
Method #2 (Normal Array)
Method #3 (Associative Array)
'Tunisia', 'us' => 'United States', 'fr' => 'France' ); echo ''; ?>
Aren’t these all the same thing? I don’t see any significant differences other than the names of the variables.
Walk it out.
$codes = array('tn','us','fr'); $names = array('Tunisia','United States','France');
array_walk($codes, function ($code,$key) use ($names) < echo ''; >);
array_walk($codes, function ($code,$key,$names)< echo ''; >,$names);
array_walk(array_combine($codes,$names), function ($name,$code)< echo ''; >)
array_walk(array_combine($codes,$names), function ($name,$code)< @$opts = ''; >) echo "";
'; foreach(array_keys($codes) as $i) < echo ''; echo ($i + 1); echo ' '; echo $codes[$i]; echo ' '; echo $names[$i]; echo ' '; > echo ''; ?>
foreach only works with a single array. To step through multiple arrays, it’s better to use the each() function in a while loop:
each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.