开发者

Reset/remove all values in an array in PHP

开发者 https://www.devze.com 2023-02-04 16:45 出处:网络
I have an array_flipped array that looks something like: { \"a\" => 0, \"b\" => 1, \"c\" => 2 }

I have an array_flipped array that looks something like:

{ "a" => 0, "b" => 1, "c" => 2 }

Is there a standard function that I can use so it looks like (where all the values are set to 0?):

{ "a" => 0, "b" => 0, "c" => 0 }

I tried using a foreach loop, but if I remember correctly from other programming languages, you shouldn't be开发者_运维知识库 able to change the value of an array via a foreach loop.

foreach( $poll_options as $k => $v )
  $v = 0; // doesn't seem to work...

tl; dr: how can I set all the values of an array to 0? Is there a standard function to do this?


$array = array_fill_keys(array_keys($array), 0);

or

array_walk($array, create_function('&$a', '$a = 0;'));


You can use a foreach to reset the values;

foreach($poll_options as $k => $v) {
  $poll_options[$k] = 0;
}


array_fill_keys function is easiest one for me to clear the array. Just use like

array_fill_keys(array_keys($array), "")

or

array_fill_keys(array_keys($array), whatever you want to do)

foreach may cause to decrease your performance to be sure that which one is your actual need.


Run your loop like this, it will work:

foreach( $poll_options as $k => $v )
    $poll_options[$k] = 0;

Moreover, ideally you should not be able to change the structure of the array while using foreach, but changing the values does no harm.


As of PHP 5.3 you can use lambda functions, so here's a functional solution:

$array = array_map(function($v){ return 0; }, $array);


You have to use an ampersand...

foreach( $poll_options as &$v)
  $v = 0;

Or just use a for loop.


you can try this

foreach( $poll_options as $k => &$v )
    $v = 0; 

Address of $v


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

Would be the least manual way of doing it.


There are two types for variable assignment in PHP,

  1. Copy
  2. Reference

In reference assignment, ( $a = &$b ), $a and $b both, refers to the same content. ( read manual )

So, if you want to change the array in thesame time as you doing foreach on it, there are two ways :

1- Making a copy of array :

foreach($array as $key=>$value){
        $array[$key] = 0 ; // reassign the array's value
}

2 - By reference:

foreach($array as $key => &$value){
        $value = 0 ;
}
0

精彩评论

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