I tried to use a foreach loop on a multi-dimensional array, and found out that it didn't exactly worked out the way that I expected. Is there a foreach loop for multi-dimensional arrays, or another way to do this?
$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";
foreach($array as $a) {
echo $a."<br>";
}
Result:
Nothing
Needed Result:
a
b
c
You could also try this:
foreach($array[0] as $key => $value){
echo $value . "<br>":
}
$array in this code you're accessing the key of 0,0,0 so it will not print it.
$array[0] in this code you're both accessing key 0,1,2 and the values a,b and c
You need two loops. One to loop the first array, and one to loop the inner one.
foreach($array as $key) {
foreach($key as $val) {
echo $val;
}
}
Try nesting another foreach...
$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";
foreach($array as $a) {
foreach($a as $val){
echo $val."<br>";
}
}
It is because $a is still an array. If you use print_r() you will see this:
foreach($array as $a) {
print_r($a);
}
Result:
Array
(
[0] => a
[1] => b
[2] => c
)
To combat the nested array you have to run a second foreach() loop to get the values:
foreach($array as $a) {
foreach($a as $value){ // loop through second array
echo $value . "</ br>";
}
}
well since no one else has mentioned it:
<?php
$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";
echo implode('<br>',$array[0]);
http://codepad.viper-7.com/SC9PLI
Related
I have two Associative array.
$a1 = array("Peter"=>"a","Ben"=>"b","Joe"=>"c");
$a2 = array("Peter"=>"5","Joe"=>"15");
and Out put result should be...
a=5
b=null
c=15
foreach($a1 as $aKey => $aValue) {
echo $aValue, '=';
echo (isset($a2[$aKey])) ? $a2[$aKey] : 'null';
echo PHP_EOL;
}
foreach($a1 as $key => $value) {
echo $a1[$key].'='.$a2[$key];
}
You will get the output, but this have nothing to do with array comparing.
I want to know what is the value of the 2nd index of my array.
I have something like this:
$a[][1]= 10;
$a[][0]= 20;
$a[][1]= 12;
$a[][0]= 25;
I want to get only the values from $a wich 2nd index is 1.
I need to do a comparison and if the answer is correct, get the value
From this example, elements will be:
$a[0][1]
$a[2][1]
I know about array_key_exists but i dont know how to use it with Multidimensional arrays.
Any help?
Thanks.
Solution I was looking for.
$a = array();
$a[][1] = b1;
$a[][0] = b2;
$a[][0] = c1;
$a[][1] = c2;
foreach ($a AS $key => $aVal )
if (array_key_exists(1,$aVal))
echo $a[$key][1] . "<br>";
Have you tried isset($a[$specified_index])?
Here is some code:
foreach ( $a AS $key => $aVal ) {
if ( array_key_exists(1,$aVal) ) {
var_dump($key,$aVal);
}
}
foreach($a as $key => $value)
{
if(isset($value[1]))
{
if($value[1] == 1)
{
echo "value is 1";
}
else
{
echo "value is not 1 but is ".$value[1];
}
}
}
thx to #Havelock
This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
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.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.
I have several arrays: $n, $p, $a
Each array is the same:
$n = array()
$n['minutes'] = a;
$n['dollars'] = b;
$n['units'] = c;
$p = array()
$p['minutes'] = x;
$p['dollars'] = y;
$p['units'] = z;
etc...
I also have a simple array like this:
$status = array('n', 'p', 'a');
Is it possible for me to use the $status array to loop through the other arrays?
Something like:
foreach($status as $key => $value) {
//display the amounts amount here
};
So I would end up with:
a
x
b
y
c
z
Or, do I need to somehow merge all the arrays into one?
Use:
$arrayData=array('minutes','dollars','units');
foreach($arrayData as $data) {
foreach($status as $value) {
var_dump(${$value}[$data]);
}
}
foreach($n as $key => $value) {
foreach($status as $arrayVarName) (
echo $$arrayVarName[$key],PHP_EOL;
}
echo PHP_EOL;
}
Will work as long as all the arrays defined in $status exist, and you have matching keys in $n, $p and $a
Updated to allow for $status
You could use next() in a while loop.
Example: http://ideone.com/NTIuJ
EDIT:
Unlike other answers this method works whether the keys match or not, even is the arrays are lists, not dictionaries.
If I understand your goal correctly, I'd start by putting each array p/n/... in an array:
$status = array();
$status['n'] = array();
$status['n']['minutes'] = a;
$status['n']['dollars'] = b;
$status['n']['units'] = c;
$status['p'] = array();
$status['p']['minutes'] = a;
$status['p']['dollars'] = b;
$status['p']['units'] = c;
Then you can read each array with:
foreach($status as $name => $values){
echo 'Array '.$name.': <br />';
echo 'Minutes: '.$values['minutes'].'<br />';
echo 'Dollars: '.$values['dollars'].'<br />';
echo 'Units: '.$values['units'].'<br />';
}
For more information, try googling Multidimensional Arrays.