alan alan - 1 year ago 87
PHP Question

Trouble Addressing Associate Array element returned from call in PHP

I want to use an associative array element that I return from api call to compare to a string value like this:

<!-- Check If there are any todo items. If not skip Todo list markup. =====-->
if ($todo_items['todo_id'] == '1234567') {
//This value indicates no todo items for person
else {
//markup to render todo item list

This causes a " Notice: Undefined index: todo_id in /var/www/todo_client/todo.php on line 80.
I put in a var_dump($todo_items) in and results are:

array (size=1)
0 =>
public 'todo_id' => string '1234567' (length=7)

Does anyone know why I am not able to access $todo_items['todo_id']?

Answer Source

From the API you're receiving an array of stdClasses so if you have just one item returned back, you can do something like this to test the value:

$result = $todo_items[0];
if ($result->todo_id == '1234567')  {/*...*/}

When there are (or can be) multiple items being returned you can iterate through the array ($todo_items) and do this test for every one of them:

foreach($todo_items as $item) {
   if ($result->todo_id == '1234567') {/*...*/}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download