0

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
        )
)
3
  • 1
    Your array structure seems overly complicated. Is the last name always in the second spot? Commented Jun 29, 2014 at 18:51
  • I cannot change the array, it's from an external source. Commented Jun 29, 2014 at 18:53
  • Duplicate. already answered here stackoverflow.com/questions/6661530/… Commented Jun 29, 2014 at 18:58

3 Answers 3

1

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'];
Sign up to request clarification or add additional context in comments.

2 Comments

Nicely done. Is this a subtle hint that the original data set might be better off as a simple associative array instead of an indexed array containing a small associate arrays as data sets?
This is the method I went for in the end. Thank you very much.
0

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);

Comments

0

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']
  }` 

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.