开发者

Replace all values in a flat array with 0

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
]


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

Alternative:

$array = array_map(create_function('', 'return 0;'), $array);


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;
}


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

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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜