-2

I am getting the follow PHP notice as a result of testing migration to PHP 7.4:

Notice: Only variables should be passed by reference

On line:

$row->type = end(explode(",",(implode(array_slice(explode ( ':',  $row->global_id), -2, 1)))));

This is in:

  $roots = array();
    foreach ($data as $row) {   
        $row->type = end(explode(",",(implode(array_slice(explode ( ':',  $row->global_id), -2, 1)))));
        if ($row->parent_global_id === null) {
            $roots[]= $row;
        } else {
            $data[$row->parent_global_id]->children[] = $row;
        }
        unset($row->parent_global_id);
        unset($row->global_id);
    }

How should that line be written for PHP 7?

IlludiumPu36
  • 4,196
  • 10
  • 61
  • 100
  • Is this `explode ( ':'` correct? Should that space be there after explode? – Sam020 Nov 17 '22 at 08:55
  • yes, it works, just want to remove the notice – IlludiumPu36 Nov 17 '22 at 08:55
  • 2
    `end()` needs an array in a variable, because it will change it. It [says so in the manual](https://www.php.net/manual/en/function.end). – KIKO Software Nov 17 '22 at 08:57
  • using end with explode in the same line will throw such warning. Move the ``end()`` to the next line. Or use ``@`` before the ``@end(explode(.....)`` to suppress the warning – OMi Shah Nov 17 '22 at 08:58
  • @OMiShah: That is truly bad advice. You might be supressing this notice, but you might also suppress other problems you need to know about. – KIKO Software Nov 17 '22 at 09:00
  • @KIKOSoftware, yes you're right, and I don't really RECOMMEND but if he wish so. – OMi Shah Nov 17 '22 at 09:01
  • 3
    As much for readability as anything it makes sense to break down that complex statement into it's constituent parts. Perhaps it will be 5 lines rather than one but easier to follow for others later if they need to debug. – Professor Abronsius Nov 17 '22 at 09:09
  • @ProfessorAbronsius I wholeheartedly agree with that. It can probably be simplified a lot as well. – KIKO Software Nov 17 '22 at 09:09

1 Answers1

1

end moves the internal pointer of an array.

So you have do $result = explode(); $row->type = end($result);

Then the notice will be no more showing up.

https://www.php.net/manual/de/function.end.php

Related functions: reset(), next(), prev()

Foobar
  • 769
  • 1
  • 4