2

I am trying to retrieve a value from an Array. Here is the code:

$opt=get_records_sql($sql1);

print_object($opt);

$n = count($opt);
if (empty($opt)){
    echo 'No options selected';
}
else{
    $optno = $opt["subjectid"];
    echo '<br>$optno = '.$optno;
}

I tried to use: $opt["subjectid"] but I get the following error:

Notice: Undefined index: subjectid

Contents of array:

Array
(
    [1] => stdClass Object
        (
            [uname] => JHollands06
            [tutor] => M LSt
            [subjectid] => 1
            [year] => 2010
            [optid] => 1
        )

)

How to I fetch the data subjectid which has value 1?

3 Answers 3

9

Method 1: Convert the object to an array by casting it.

$opt[1] = (array) $opt[1];
echo $opt[1]['subjectid'];

To convert all objects in an array (if there are more than one):

foreach ($opt as $k => $val) {
    $opt[$k] = (array) $val;
}

Method 2: Simply call it as an object like it is already assigned.

echo $opt[1]->subjectid

There is a difference between an array and an object. An object contains variables that have to be called using the '->' and an array contains values which are associated with a specific key. As your output states, you have an array containing an stdClass object, not another array.

Sign up to request clarification or add additional context in comments.

Comments

1

$opt is an array of rows. So you'd do something like this:

foreach($opt as $row)
{
   echo $row['subjectid'];
}

Or just use an index:

$opt[0]['subjectid'];

Comments

1

Your array contains rows. It's not just one row. So you need to index it by row first.

edit: your rows are objects, my bad. So it should be

$opt[1]->subjectid

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.