Jump to content

[SOLVED] Simble question about foreach


JeditL

Recommended Posts

Hi, I'm still a newbie to PHP and I got a simple problem that I just can't get solved.

 

I got an associative array and I would like to use (for example print) only particular fields of the array.

For example my array has fields "name", "address" etc. and it holds many names and addresses. I would like to echo all the names from the array but nothing else.

 

I've tried:

 

foreach ($array as $field)

        echo $field['name'];

 

and I've tried aswell:

 

foreach ($array['name'] as $field

        echo $field;

 

but they just won't work. Please help me. I know this is simple problem and I hope you can help me easily. Thanks to anyone replying.

Link to comment
Share on other sites

Try this:

foreach ($array as $key => $value) {

      if ($key == 'name') {

             echo "$key: $value<br />";
      }

}

 

It may be different depending on the scope of your array however.  If the above doesn't do it then add var_dump($key); and var_dump($value); inside the foreach statement to find out how your array is structured.

Link to comment
Share on other sites

I solved my problem. It was mysql associative array so your method didn't work on that. My bad, I didn't tell about that cause I thought it wouldn't matter but it did. I used this:

 

while($row = mysql_fetch_array($result, MYSQL_ASSOC))

    echo $row['name'];

 

I would still like to know how to display the data of $result array with foreach() if it is even possible. Is it?

Link to comment
Share on other sites

Hi, thanks for the reply. ;) What I'm trying to solve here is:

 

What if I had multidimensional array like this:

 

$array['row1'][0]=0;

$array['row1'][1]=1;

$array['row1'][2]=2;

$array['row2'][0]=3;

$array['row2'][1]=4;

$array['row2'][2]=5;

 

and I would like to use foreach to display every field of the array. How do I do that using foreach?

 

 

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.