0

$cars7=array( array( array('a1','b1','c1'), array('a2','b2','c2'), array('q'=>'a','b'=>'b','c'=>'c') )
);

I tried the for loop with how we write the code for index array same i tried for mixed multidimensional array by showing error could not convert string to array.

----php multidimensional for loop.

$cars7=array(
          array(
          array('a1','b1','c1'),
          array('a2','b2','c2'),
          array('q'=>'a','b'=>'b','c'=>'c')
 )        
);



 for($i=0;$i<=count($cars7)-1;$i++) 
             {
             for($j=0;$j<=count($cars7[0])-1;$j++) 
            {
             echo $cars7[$i][$j].'<br><br>';

        }

    }

I don't know how to loop multidimensional array which contains index array and associative array.

I need help from expertise, Please correct the above code.

2 Answers 2

1

This might help:

$cars[0] is:

array(
      array('a1','b1','c1'),
      array('a2','b2','c2'),
      array('q'=>'a','b'=>'b','c'=>'c')
)   

$cars[0][0] is:

array('a1','b1','c1')

$cars[0][0][0] is:

a1

You've got the right idea, you just need to start your loop a little "deeper". And to loop through the arrays, use foreach:

foreach ( $cars[0] as $test )
{
   foreach ( $test as $entry )
   {
      echo $entry.'<br><br>';
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

what if we need $cars[0][0] and $cars7[0][2]['q'] in loop any can we separate condition for index and associative two different.
I hope you got my point. like i need to access index array sometimes and associative sometime dynamically. if we put condition like if(something is associative array) possible.
There's no function to test if an array is associative or not, but you can use key (php.net/manual/en/function.key.php) with if statements to figure out whether you want to keep the key or not.
0

Another option to get all the values is to use array_walk_recursive

$cars7 = array(
    array(
        array('a1', 'b1', 'c1'),
        array('a2', 'b2', 'c2'),
        array('q' => 'a', 'b' => 'b', 'c' => 'c')
    )
);

array_walk_recursive ($cars7, function($value){
    echo $value . '<br>';
});

Result

a1
b1
c1
a2
b2
c2
a
b
c

Php demo

Comments

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.