4

Is there any default function to clear only the values of an array?

For example:

$array = [
    10,
    3,
    3,
    34,
    56,
    12
];

Desired result:

[
    0,
    0,
    0,
    0,
    0,
    0
]
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
ArK
  • 20,698
  • 67
  • 109
  • 136

4 Answers4

8
$array = array_combine(array_keys($array), array_fill(0, count($array), 0));

Alternative:

$array = array_map(create_function('', 'return 0;'), $array);
deceze
  • 510,633
  • 85
  • 743
  • 889
3

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
  • 31,386
  • 20
  • 94
  • 126
1
$array = array_fill(0, count($array), 0);

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

Victor Stanciu
  • 12,037
  • 3
  • 26
  • 34
  • 2
    Although the OP didn't say so, I'm assuming the keys might not be continuously numeric. This solution would destroy the keys. – deceze May 31 '10 at 07:08
  • The code above works for your example (non-associative array). If you want to preserve keys, deceze's solution is correct. – Victor Stanciu May 31 '10 at 07:08
0

You can use array_map() to overwrite all values with 0. This approach preserves the original keys.

Code: (Demo)

$zeros = array_map(fn() => 0, $array);

var_export($zeros);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136