0

I've done this a million times but for some reason I can't get this to work today...

I have this associative array

 Array
 (
     [0] => stdClass Object
         (
             [registrantKey] => 106569618
             [firstName] => xxx
             [lastName] => yyy
             [email] => x@x.x

         )

     [1] => stdClass Object
         (
             [registrantKey] => 106975808
             [firstName] => qqq
             [lastName] => ppp
             [email] => aaa@aaa.com

         )
 ...
 ...

I just want to get the first name of each one of them, im using a foreach loop but doesn't really let me get what I want.

Any ideas?

 foreach($array as $key=>$value){
      echo $value['firstName'];
 }
matt
  • 2,312
  • 5
  • 34
  • 57

5 Answers5

0

For this case, your array element isn't an array but an object.

As such, it should be:

foreach($array as $key=>$value){
    echo $value->firstName;
}
uzyn
  • 6,625
  • 5
  • 22
  • 41
0
foreach($array as $key=>$value){
  echo $value->firstName;
}

You have stdClass Objects as array elements and not associative arrays so you need the option notation: $value->firstName

You could also convert the stdClass Object to array by type casting:

foreach($array as $key=> (array) $value){
  echo $value['firstName'];
}
Besnik
  • 6,469
  • 1
  • 31
  • 33
0

Try this:

$value->firstName;
Matt
  • 6,993
  • 4
  • 29
  • 50
0

You can also do:

foreach($array as $key=> (array) $value){
     echo $value['firstName'];
}

This will typecast your object to an array.

Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87
0
<?php 

 $array = (array)$array; 
 $firstNames = array();
 foreach($array as $a)
 {
     $firstNames[] = $a['firstName'];
 }
 print_r($firstNames);

?>
Johndave Decano
  • 2,101
  • 2
  • 16
  • 16