PHP - Get values from Array

PHP - Get values from Array



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:


$opt["subjectid"]


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



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.



$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'];



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


$opt[1]->subjectid






Get Fatal error: Cannot use object of type stdClass as array

– CLiown
Mar 26 '10 at 19:30



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế