skip to Main Content

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


  1. 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"]] : []
    );
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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',
    )
    

    If you really do want a non-associative, indexed array, just pass the result of array_intersect_key to array_values:

    $new_arr = array_values(array_intersect_key($source_arr, ['Car'=>'','State'=>'']));
    
    array (
      0 => 'Volvo',
    )
    

    Check both methods here.

    Login or Signup to reply.
  4. Yes, you absolutely can "push nothing" conditionally.

    Use the splat operator to unpack an array with zero or one element in it.

    Code: (Demo)

    $source_arr = ["Car" => "Volvo", "City" => "Stockholm", "Country" => "Sweden"];
    $new_arr    = [];
    
    array_push(
        $new_arr,
        ...key_exists("Car",   $source_arr) ? [$source_arr["Car"]] : [],
        ...key_exists("State", $source_arr) ? [$source_arr["State"]] : []
    );
    
    var_export($new_arr);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search