Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array clear

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
]
like image 721
ArK Avatar asked Dec 17 '22 00:12

ArK


2 Answers

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

Alternative:

$array = array_map(create_function('', 'return 0;'), $array);
like image 86
deceze Avatar answered Dec 27 '22 10:12

deceze


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;
}
like image 35
Ondrej Slinták Avatar answered Dec 27 '22 11:12

Ondrej Slinták