Robert Chabal Robert Chabal - 25 days ago 9
PHP Question

I'm pulling my hair out with basic error

I think i'm to old or i'm just stupid but i can't understand why i can't loop on an simple array.

I have this code:

$results = [];
for ($i = 0; $i < count($links); $i++) {
$results[] = [
'site' => $links[$i],
'pda' => $data[$i]->pda
];
}


The $links array contains a list of urls and $data contains a list of values like this:

array(3) {
0 => object(stdClass)
{
"pda" => int 100
}
1 => object(stdClass)
{
"pda" => int 100
}
2 => object(stdClass)
{
"pda" => int 1
}
}


EDIT: This is the print_r($data) content...it seems that some of you don't understand the dump from above and prefer the print_r solution :-|

Array
(
[0] => stdClass Object
(
[pda] => 100
)

[1] => stdClass Object
(
[pda] => 1
)

[2] => stdClass Object
(
[pda] => 100
)

)


If i do $data[$i]->pda in the loop i get "Cannot use object of type stdClass as array" error.

If i try to access it as an object, i get "Trying to get property of non-object" error.

Bottom line, am i stupid or i'm going crazy?!

Thank you!

Answer

Little bit extended answer from comments:

You probably have a different number of $links than $data. Debug with a simple if else condition before accessing $data[$i] and dump the actual result if it fails.

for ($i = 0; $i < count($links); $i++) {
  if (isset($data[$i])) {
      $results[] = [
       'site' => $links[$i],
       'pda'  => $data[$i]->pda
    ];
  } else {
    // Somethings wrong
    var_dump($i);
    var_dump($links);
    var_dump($data);
  }

}

So if your function gets called several times, you are dumping the actual data when the error happens.

Comments