1

In the foreach I want to access the array value and the array looks like this.

Array
(
    ['name'] => John Doe
    ['age'] => 25
    ['from'] => Australia
)

How do I get the value of name age and from?

With echo $item['name'] and return Undefined index: name.

5
  • 4
    It would be helpful to see your foreach loop. Commented Mar 2, 2014 at 15:41
  • It's a $_POST from name[], age[], from[]. I want to preview it back if have an error to the form. Commented Mar 2, 2014 at 15:47
  • 1
    Ok, but you still need to show the foreach loop for anyone to understand your problem. As it is now, there is no possible way to figure out what's wrong without guessing. Commented Mar 2, 2014 at 15:51
  • If just 3 values from form are in question, why you need loop at all? Commented Mar 2, 2014 at 15:56
  • @Anonymous an example pastebin.com/Pe6UgjQA Commented Mar 2, 2014 at 16:00

1 Answer 1

2

If you are foreaching over that array you just want ot echo the item:

$the_array = array( 'name'=> "John Doe", 'age' => 25, 'from' => 'Oz');
foreach($the_array as $item){
   //the first iterations will echo out $the_array['name'], 
   //second $the_array['age'], etc...
   echo $item;

  //in this loop $item['name'] has no meaning if that's what you're doing....
} 

Now if it's really an array of arrays you can do this

$the_array = array(array( 'name'=> "John Doe", 'age' => 25, 'from' => 'Oz'));
foreach($the_array as $item){
   foreach($item as $key=>$value){
       echo $key." ".$value;
   }

}

If you're not positive the values you want to echo are being set but dont want the inner loop you might:

foreach($the_array as $item){
   $name =isset($item['name']) ?$item['name'] : null;
    echo $name;
    $age =isset($item['age']) ?$item['age'] : null;
    echo $age;

    //...etc...


}
Sign up to request clarification or add additional context in comments.

6 Comments

With echo $item it's return to array to string conversion. pastebin.com/Pe6UgjQA
var_dump $item What do you get?
array(3) { ["'name'"]=> string(8) "john doe" ["'age'"]=> string(2) "25" ["'from'"]=> string(6) "region" }
I suspect you're using post array or something, and a value;s not being set, so just check for existance before using @user3337623
Ahaa.. the value is appearing with duplicate of current amount of my rows. Let me see if something wrong to my session. Thanks Ray for the hints.
|

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.