How to handle array_shift() on Null ?
P粉300541798
P粉300541798 2024-02-25 22:27:30
0
2
395

Please take a look at this code:

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

It was running fine 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, given null in /path/to/qanda.php:469

Any idea how to fix it?

P粉300541798
P粉300541798

reply all(2)
P粉237029457

The most basic solution is to replace the null value with an empty array to match the type requirements:

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

You can also create an 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 the return value of array_shift. The loop body will only run once. Maybe just use a conditional?

if (isset($newvar)) {
P粉696146205

Just use an empty array:

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

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!