tags:

views:

132

answers:

3
+4  Q: 

php array clear

Is there any default function to clear only the values of an array. For ex arr{10,3,3,34,56,12} to arr{0,0,0,0,0,0}

A: 
$array = array_fill(0, count($array), 0);

This creates an array of the original one's size filled with zeroes.

Victor Stanciu
Although the OP didn't say so, I'm assuming the keys might not be continuously numeric. This solution would destroy the keys.
deceze
The code above works for your example (non-associative array). If you want to preserve keys, deceze's solution is correct.
Victor Stanciu
+8  A: 
$array = array_combine(array_keys($array), array_fill(0, count($array), 0));

Alternative:

$array = array_map(create_function('', 'return 0;'), $array);
deceze
+3  A: 

To answer your original question: No, there isn't any default PHP function for this. However, you can try some combination of other functions as other guys described. However, I find following piece of code more readable:

$numbers = Array( "a" => "1", "b" => 2, "c" => 3 );

foreach ( $numbers as &$number ) {
    $number = 0;
}
Ondrej Slinták