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',
// )
?>