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