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
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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.