1

If I have:

$data = array(
  'id01' => array(
    'firstName' => 'Eric',
    'lastName' => 'Smith',
  ),
  'id02' => array(
    'firstName' => 'John',
    'lastName' => 'Turner',
  ),
);

foreach ( $data as $key){
    print "$key[firstName]<br>";
    echo $key[0];
}

The $key[0] part is not working...basically i'm trying to output id01, then id02, basically the id part of the array that the forloop is processing...

Any ideas on the correct syntax?

1
  • Shouldn't you use $key[firstName] ? Commented Apr 11, 2011 at 16:09

4 Answers 4

5

What you need is

foreach ($data as $key => $val){
    print "$val[firstName]<br>"; //changed to $val
    echo $key; //prints id01, id02
}
Sign up to request clarification or add additional context in comments.

Comments

1

There is no key for 0 , just first and last name - you need to do this

foreach ($data as $key => $value)
{
    echo "Key is " . $key . ", value of firstName 
          is " . $value["firstName"] . "<br />";
}

Comments

1

something like this?

foreach ( $data as $key=>$value){
    print "$value[firstName]<br>";
    echo $key.'<br />';
}

Comments

0

Try:

foreach ( $data as $key=>$value)

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.