Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle array_shift() on Null?

Please take a look at this code:

$end = isset($newvar) ? array($newvar) : null;
while($ends = array_shift($end)){
  ...

It was working well when I was using PHP 7.2, but after upgrading to 8.1, it throws:

PHP Fatal error: Uncaught TypeError: array_shift(): Argument #1 ($array) must be of type array, null given in /path/to/qanda.php:469

Any idea how can I fix it?

like image 310
Martin AJ Avatar asked Sep 11 '26 20:09

Martin AJ


2 Answers

Just use an empty array instead:

$end = isset($newvar) ? array($newvar) : [];

array_shift will return null on the first call with an empty array as input, so the loop will not execute.

like image 198
Nick Avatar answered Sep 14 '26 13:09

Nick


The most basic solution would be to replace the null value with an empty array to comply with the type requirements:

$end = isset($newvar) ? array($newvar) : [];
while($ends = array_shift($end)){

You could also create the array and use the null coalescing operator on $newvar:

$end = [$newvar ?? null];
while($ends = array_shift($end)){

But I don't understand why you would create an array with a single value and then create a loop using array_shift's return value. The loop body will only run once. Maybe just use a condition ?

if (isset($newvar)) {
like image 35
AymDev Avatar answered Sep 14 '26 11:09

AymDev