phparraysfilter

Create a new array of by removing the zero values from another array


I have an array that could contain zero values.

$array = array(3=> 1000, 5=> 0, 6=> 5000, 7 => 0);

Since the code that uses that array can't manage fields set as 0, I need to remove them. (I thought to store the field with 0 as value in a temp array):

$zero_array = array();
foreach ($array as $k => $s) {
    $zero_array[$k] = $k;
    unset($stack[$k]);
}

After the core code has runned I want to put back the filed that had 0 as value in the same position as they were.

The core code returns an array like this:

$output = array(3 => 10, 6 => 50);

I'd like to add the old keys and get this:

$output = array(3 => 10, 5 => 0, 6 => 50, 7 => 0);

Solution

  • Just use array_filter in this situation to remove the 0 values:

    $old_array = array(3 => 1000, 5=> 0, 6=> 5000, 7 => 0);
    $new_array = array_filter($old_array);
    
    // Now: $new_array = Array ( [3] => 1000 [6] => 5000 )
    

    Then, do the stuff you want to $new_array

    // Core code: Divide each element by 100:
    $new_array = array(3 => 10, 6 => 50);
    

    Then use the array union operator followed by ksort to get your desired array:

    $array = $new_array + $old_array;
    ksort($array);
    
    // Now: Array ( [3] => 10 [5] => 0 [6] => 50 [7] => 0 )
    

    Note: If Array ( [3] => 10 [6] => 50 [5] => 0 [7] => 0 ) is acceptable (IE. all the same key value pairs as your desired array, just in a different order), then you can skip the call to ksort.