George
George

Reputation: 27

Getting an element from array in PHP

With the following array, how would I just print the last name?

Preferably I'd like to put it in the format print_r($array['LastName']) the problem is, the number is likely to change.

$array = Array
(
    [0] => Array
        (
            [name] => FirstName
            [value] => John
        )

    [1] => Array
        (
            [name] => LastName
            [value] => Geoffrey
        )

    [2] => Array
        (
            [name] => MiddleName
            [value] => Smith
        )
)

Upvotes: 0

Views: 61

Answers (3)

dave
dave

Reputation: 64657

I would normalize the array first:

$normalized = array();
foreach($array as $value) {
  $normalized[$value['name']] = $value['value'];
}

Then you can just to:

echo $normalized['LastName'];

Upvotes: 1

Maggz
Maggz

Reputation: 175

This array is not so easy to access because it contains several arrays which have the same key. if you know where the value is, you can use the position of the array to access the data, in your case that'd be $array[1][value]. if you don't know the position of the data you need you would have to loop through the arrays and check where it is.. there are several solutions to do that eg:

 `foreach($array as $arr){
     (if $arr['name'] == "lastName") 
      print_r($arr['value']
  }` 

Upvotes: 0

bsoist
bsoist

Reputation: 785

If you are not sure where the lastname lives, you could write a function to do this like this ...

function getValue($mykey, $myarray) {
    foreach($myarray as $a) {
        if($a['name'] == $mykey) {
            return $a['value'];
        }
    }
}

Then you could use

print getValue('LastName', $array);

Upvotes: 0

Related Questions