Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php 8.1 - explode(): Passing null to parameter #2 ($string) of type string is deprecated [duplicate]

Tags:

php

php-8.1

Coming across some deprecated errors with 8.1 I want to address.

PHP Deprecated: explode(): Passing null to parameter #2 ($string) of type string is deprecated in...

//explode uids into an array
$comp_uids = explode(',', $result['comp_uids']);

$result['comp_uids'] in this case is empty which is why the null error shows. I'm not sure why they are deprecating this ability, but what is the recommended change to avoid this? I'm seeing similar with strlen(): Passing null to parameter #1 ($string) of type string is deprecated and a few others using 8.1.

like image 421
user756659 Avatar asked Sep 02 '25 15:09

user756659


2 Answers

Use the null coalescing operator to default the value to an empty string if the value is null.

$comp_uids = explode(',', $result['comp_uids'] ?? '');
like image 107
Barmar Avatar answered Sep 05 '25 04:09

Barmar


Just cast the parameter as string, will convert null to ''.

$comp_uids = explode(',', (string)$result['comp_uids']);
like image 22
Matthew Ho Avatar answered Sep 05 '25 06:09

Matthew Ho