Jump to content

Foreach and Array


tqla

Recommended Posts

Hello, I have an array called $data that looks like this.

 

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)

 

I wish to do a foreach look on this part:

 

    [1] => Array
        (
            [0] => c
            [1] => d
        )

 

When I do

 

foreach ($data as $row)...

 

I get everything in the array.

 

When I do

 

foreach ($data[1] as $row)... or foreach ($data['1'] as $row)...

 

I get nothing.

 

What is the proper way?

 

Thanks.

Link to comment
https://forums.phpfreaks.com/topic/267818-foreach-and-array/
Share on other sites

Obviously print_r prints this:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)

 

My question is how do do a foreach loop on this part:

 

    [1] => Array
        (
            [0] => c
            [1] => d
        )

Link to comment
https://forums.phpfreaks.com/topic/267818-foreach-and-array/#findComment-1373959
Share on other sites

$myarray = array(
            array('a', 'b'),
            array('c', 'd'),
            array('e', 'f')
        );
        
foreach ($myarray as $row)  {
    foreach ($row as $x)  {
        echo  "$x "; 
    }
    echo '<br />';
}

 

result

a b

c d

e f

 

Link to comment
https://forums.phpfreaks.com/topic/267818-foreach-and-array/#findComment-1373985
Share on other sites

<?php
$myarray = array(
            array('a', 'b'),
            array('c', 'd'),
            array('e', 'f')
        );
        
foreach ($myarray[1] as $x)  {
echo  "$x "; 
}
?>

 

It works that way, which is why I said you need to post your code if when you attempt to do that, it doesn't work.

Link to comment
https://forums.phpfreaks.com/topic/267818-foreach-and-array/#findComment-1373990
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.