Forum Moderators: coopster

Message Too Old, No Replies

Casting variable to array using ? ?

         

csdude55

7:48 pm on Feb 12, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I had a section like this:

if (!empty($foo))
$bar = (array) $foo;

elseif (!empty($lorem))
$bar = $lorem;


I wanted to shorten it using ?:

$bar = (array) $foo ? $lorem;


but (array_ $foo results in an empty array when $foo is null or false. Which makes perfect sense, but it's not the result I'm wanting.

Since it has to be an array no matter what, my backup plan was this:

$bar = $foo ? $lorem;
settype($bar, 'array');

or the slightly shorter but harder to read:

$bar = (array) ($foo ? $lorem);


Thoughts, suggestions, or alternatives? For me, processing speed is King, file size is Queen, readability is... Prince of Wales, I guess? I dunno, I'm American :-/ I should have gone with President, VP, and Speaker, but I got lost in the metaphor and it's too far to go back now! LOL

Dimitri

10:54 am on Feb 18, 2023 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



For such small piece of code, you should let the PHP optimizer do its work.

Also, your short version is not doing the same as the if thenif . Because I guess that both foo and lorem can be empty, then bar, should be undefined.

csdude55

6:18 pm on Feb 18, 2023 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Sorry for the posting error, those ? in the code should be doubled: ??.

you should let the PHP optimizer do its work

What do you mean?

your short version is not doing the same as the if thenif . Because I guess that both foo and lorem can be empty, then bar, should be undefined.

Good point, it would result in an empty array, too. I can't think of a modification without using a second line:

$bar = (array) ($foo ?? $lorem);
if (empty($bar)) $bar = false;

Dimitri

6:46 pm on Feb 18, 2023 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



I think this is what you would like (test to be sure this is doing what you want).
$bar = ( ( $foo ?? false ) !== false ) ? $foo : ( $lorem ?? false ) ;


But, personally, I think this is making the expression unnecessarily hard to read. This is important, when you write programs (no matter the language), to keep the code easy to read and understand.

What do you mean?

PHP (should) come with OPcache enabled by default (PHP 5.5 and above). Beside caching the bytecode of the PHP scripts, it also applies a series of optimizations to the code : [npopov.com...] . PHP 8.1 includes the optimizer in the core PHP engine. In other words, it means that the script you write in PHP , is "optimized" by the PHP engine. So, for small optimization, I think it 's not worth bothering tweaking your PHP code, the PHP engine might already do the optimizing job.