Home > Software design >  Is it possible to append nothing to an array?
Is it possible to append nothing to an array?

Time:12-15

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

?>

CodePudding user response:

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.

$new_array = array_merge($new_array, 
    key_exists("Car", $source_arr) ? [$source_arr["Car"]] : [],
    key_exists("State", $source_arr) ? [$source_arr["State"]] : []
);

CodePudding user response:

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:

$new_arr = array_filter([
    $source_arr["Car"] ?? null,
    $source_arr["State"] ?? null,
]);

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.

CodePudding user response:

Even better, get everything in one line using array_intersect_key

$source_arr = ["Car" => "Volvo", "City" => "Stockholm", "Country" => "Sweden"];
$new_arr    = array_intersect_key($source_arr, ['Car'=>'','State'=>'']);

var_export($new_arr);

The above outputs the following:

array (
  'Car' => 'Volvo',
)

Check it here.

  •  Tags:  
  • php
  • Related