Home  >  Q&A  >  body text

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 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粉300541798P粉300541798211 days ago399

reply all(2)I'll reply

  • P粉237029457

    P粉2370294572024-02-26 19:37:09

    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)) {
    

    reply
    0
  • P粉696146205

    P粉6961462052024-02-26 18:54:55

    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.

    reply
    0
  • Cancelreply