Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any idea how can I fix it?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading