0

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);
2
  • Tried array_merge($output,$zero_array) ? Commented Jan 8, 2012 at 20:01
  • Keep your original array the way it is, then create a copy of that array without the 0 values to use in your code. You can unset() that array when your code has completed use of it and you still have your original for whatever else you need to do. Commented Jan 8, 2012 at 20:01

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.