1

For example i did this code

<?php
$arr= [12, 24,17,49];
foreach ($arr as $value) {
    if ($value % 2 == 0) 
        $max = $value + 1;
    else
        $max = $value - 1;
    var_dump($max);
    echo $max;
}
?>

it works perfectly but why when it comes to multidimensional arrays like these:

<?php
$arr= array (
    array (12, 24, 17, 49 ),
    array (10, 4, 99, 74)
);
foreach ($arr as $value) {
    if ($value % 2 == 0) 
        $max = $value + 1;
    else
        $max = $value - 1;
    var_dump($value);
    echo $value;
}
?>

Code just wont work,tried alot of variations, dont know what clue i am missing.

4
  • $value is an array in the second example because it is multi-dimensional. The foreach goes 1 level in so on the first one your get 12 then 24, etc. On the second on you get array (12, 24, 17, 49 ) then array (10, 4, 99, 74). Commented Jun 27, 2018 at 21:06
  • as well as the answer below you might want to look in to "recursive" functions Commented Jun 27, 2018 at 21:17
  • It may be helpful if you add a brief description of what the code is supposed to do. Commented Jun 27, 2018 at 21:35
  • A good way to get a visual of this would be to print_r($value), and you will see that $value is an array with 4 elements in it. Commented Jun 27, 2018 at 21:43

1 Answer 1

1

You have to go one level deeper because you have nested arrays in an array

Your code will be

 $arr= array(
       array (12, 24, 17, 49 ),
       array (10, 4, 99, 74)
     );

foreach ($arr as $inner_arr) 
{
   foreach ($inner_arr as $value) 
   {
     if ($value % 2 == 0) 
       $max = $value + 1;
     else
       $max = $value - 1;

     echo $value ."<br />";
   }
 }

echo $max;

Read more at about multidimensional arrays here http://php.net/manual/en/language.types.array.php

Sign up to request clarification or add additional context in comments.

1 Comment

This is it. your first foreach loop's $value is equal to your first questions $arr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.