Search code examples
phpreadabilitycode-readability

Omitting the 'else' in PHP ternary and null coalescing operators


I was reading about and experimenting a bit with ternary and null coalescing operators in PHP.

So, instead of writing

if (isset($array['array_key']))
{
    $another_array[0]['another_array_key'] = $array['array_key'];
}
else
{
    // Do some code here...
}

and instead of shortening it with null coalescing or ternary operator I tried to further shorten the code with the null coalescing but without the 'else' part as I didn't really needed. I searched for it and found some solutions that weren't what I wanted.

I tried this and both solutions worked!

$another_array[0]['another_array_key'] = $array['array_key'] ??
$another_array[0]['another_array_key'] = $array['array_key'] ? :

print_r($another_array);

Note there is no ; at the end of the line above.

My question is: Would this be an acceptable piece of code? I think it might be hard to explain it with a comment, as it can be a burden in readability after some time.

Sorry if it's a similar question - I didn't really had time to check them all as there was quite a few suggested by Stack Overflow.

This would be the kinda 'complete' code example:

<?php

$another_array = [];

$array = [
    'name' => 'Ivan The Terrible',
    'mobile' => '1234567890',
    'email' => 'tester@test.com'
];

if (isset($array['name']))
{
    $another_array[0]['full_name'] = $array['name'];
}


$another_array[0]['occupation'] = $array['occupation'] ??
// or $another_array[0]['occupation'] = $array['occupation'] ? :

print_r($another_array);

Solution

  • Reabability, maintainability... If you want to test many possible array keys and then add them or not in a final array, nothing stops you from creating a 3rd array that will hold the keys to check and loop through it :

    <?php
    
    $another_array = [];
    
    $array = [
        'name' => 'Ivan The Terrible',
        'mobile' => '1234567890',
        'email' => 'tester@test.com'
    ];
    
    $keysToCheck = [
        // key_in_the_source_array => key_in_the_target
        'name' => 'full_name',
        'occupation' => 'occupation'
        // if you want to test more keys, just add them there
    ];
    
    foreach ($keysToCheck as $source => $target)
    {
        if (isset($array[$source]))
        {
             $another_array[0][$target] = $array[$source];
        }
    }
    
    print_r($another_array);
    

    Please take note that

    $another_array[0]['occupation'] = $array['occupation'] ??
    
    print_r($another_array);
    

    is evaluated as

    $another_array[0]['occupation'] = $array['occupation'] ?? print_r($another_array);
    

    If you add another print_r($another_array); after, you'll notice that $another_array[0]['occupation'] => true because of the return value of print_r()