Sara
Sara

Reputation: 83

Foreach loop + associative array

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.

Upvotes: 1

Views: 10925

Answers (3)

jli
jli

Reputation: 6623

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

Upvotes: 4

nine7ySix
nine7ySix

Reputation: 461

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.

Upvotes: 2

Jon Egeland
Jon Egeland

Reputation: 12613

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.

Upvotes: 1

Related Questions