Vegemike
Vegemike

Reputation: 37

How can I access individual values in an associative array in PHP?

I am pulling elements from a standard class object into an assoc array like so:

$array = $subjects;
foreach ( $array as $subject ) {

    foreach ( $subject as $prop => $val ) {
        if ( $val !== '' ) {
         echo $prop . ' = ' . $val;
         echo "<br>";
        }
    }
}

I get the result I expect from above, except what I'd like to do is echo out individual values into a table.

When I do this: echo $subject['day1']; I get this: "Cannot use object of type stdClass as array."

Where am I going wrong? Thanks in advance.

Upvotes: 1

Views: 38

Answers (2)

Vladimir Despotovic
Vladimir Despotovic

Reputation: 3498

You are trying to iterate over the $array and $array is still an object. Use this:

    $vars = get_object_vars($subjects);

to get assoc. array from the object $subjects. Then go:

foreach ($vars as $name => $value) {
    echo $name . "=" . $value;
    echo "<br>";
}

Upvotes: 0

Magd Kudama
Magd Kudama

Reputation: 3459

If it's using StdClass you'll need to do this:

$subject->day1

If you want to convert it to an array, have a look at this question: php stdClass to array

Upvotes: 1

Related Questions