I am wondering if it is possible to append "nothing" to an array, i.e. the array won’t be affected. The scenario is that I would like to use the ? :
operators to append values to an array if it exists. Otherwise nothing should be appended. I am aware that I can solve this with an ordinary if
statement without the else
part. But is there a way to tell PHP that it should append "nothing"? I’m just curious if there’s a method for this?
<?php
$source_arr = ["Car" => "Volvo", "City" => "Stockholm", "Country" => "Sweden"];
$new_arr = [];
$new_arr[] = (key_exists("Car", $source_arr)) ? $source_arr["Car"] : [];
$new_arr[] = (key_exists("State", $source_arr)) ? $source_arr["State"] : [];
// An ordinary if statement works of course:
// if (key_exists("State", $source_arr)) { $new_arr[] = $source_arr["State"]; }
// But, is it possible to use ? : and append "nothing" (i.e. not using []) if key doesn't exist?
echo "<pre>";
var_export($new_arr);
echo "</pre>";
// The above outputs (and I understand why):
// array (
// 0 => 'Volvo',
// 1 =>
// array (
// ),
// )
//
// But I want the following result (but I don't know if it's possible with ? :)
// array (
// 0 => 'Volvo',
// )
?>
4
Answers
You can’t do it when assigning to
$array[]
. You can do it with a function that takes an array argument, by wrapping the value to be added in an array, and using an empty array as the alternate value.array_merge()
is such a function.You could always add the new value (i.e., even if it’s empty) and then remove the empties with
array_filter()
when you’re done adding:Of course, the problem here is that you’ll never be able to rely on what’s in the array. Is the first element car? Is it city? Country? You’ll never know.
Even better, get everything in one line using
array_intersect_key
The above outputs the following:
If you really do want a non-associative, indexed array, just pass the result of
array_intersect_key
toarray_values
:Check both methods here.
Yes, you absolutely can "push nothing" conditionally.
Use the splat operator to unpack an array with zero or one element in it.
Code: (Demo)