1

If I have the following code:

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $name => $age){
    echo "Name: $name, Age: $age <br />";
}

How can I output specific information? Below is a wrongly written example:

foreach( $employeeAges as $name => $age ) {
     $selective = $name["Lisa"]->$age;
     $secondary = $name["Grace"]->$age;
     echo "The person you're looking for is $selective years old. And the other one is $secondary years old.";
}

As you see, I want to grab only the $value of specifics $key. The code above output the following error:

Trying to get property of non-object 

Can someone please help with this piece of code? Greatly appreciated.

0

3 Answers 3

4

If I understand you right, and you just want to get the age of a particular person, just do this:

$selective = $employeeAges["Lisa"];
$secondary = $employeeAges["Grace"];
echo "The person you're looking for is $selective years old. And the other one is $secondary years old.";

The -> operator is for accessing a named member of an object. See: http://www.php.net/manual/en/language.oop5.basic.php

As discussed in comments, to iterate through the array to find a particular key, do:

foreach ($employeeAges as $name => $age) {
    if ($name == "Grace") {
        echo $name . " is " . $age . " years old";
        break;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Embarrassing, thank you! I was just now trying to do with the for loop instead of for each. Is it possible to do with for and break when it reaches Grace and output her age?
Sure, but it defeats the purpose of the associative array. I'll update my answer with how.
There, sorry it took so long (typing on phone soft keyboard..)
2

I interpreted the question differently

<?php
//Assuming this is your array

$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

echo $employeeAges["Lisa"]; //Will output 28
echo $employeeAges["Jack"]; //Will output 16
echo $employeeAges["Grace"]; //Will output 34

You simply need to specify the key you want, and it will output the value.

Comments

1

So you want to print out just the age?

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";

$employeeAges["Grace"] = "34";

foreach($employeeAges as $name=>$age) {
  echo $age;
}

using a foreach loop like that just forces the key into $name and the value into $age without having to call on objects, hence your error.

I think @jli has a better answer suited to your question though.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.