Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: set all values in an array to something

Tags:

arrays

php

Hi want to ask if there is a way to do this without foreach ($array as $k=>$v). I know it will work but I'm looking for a more elegant way if you know. So my array was like:

1 = 231
2 = 432
3 = 324

I flipped it and it became: 231 => 1, 432 =>2, 324 => 3. Now what I need to do is to set all values to '1'

like image 268
Martin Avatar asked Jun 22 '12 14:06

Martin


People also ask

How do you change all values in an array?

To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

What is array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.

Does += work on arrays in PHP?

The + operator in PHP when applied to arrays does the job of array UNION. $arr += array $arr1; effectively finds the union of $arr and $arr1 and assigns the result to $arr .

What does => mean in PHP array?

It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.


4 Answers

You can use array_fill_keys:

$array = array(     1 => 231,     2 => 432,     3 => 324 );  $array = array_flip($array);  $array = array_fill_keys(array_keys($array), 1); 
like image 86
Rocket Hazmat Avatar answered Sep 23 '22 00:09

Rocket Hazmat


array_fill_keys() should be what you need:

$keys = array_keys($yourArray); $filled = array_fill_keys($keys, 1); 
like image 22
acme Avatar answered Sep 22 '22 00:09

acme


For PHP >5.3 you can use anonymous functions.

array_walk($array,function(&$value){$value=1;});

Note: value is passed by reference.

like image 39
MortalViews Avatar answered Sep 23 '22 00:09

MortalViews


I believe you're looking for this function: array_fill()

From the above link:

"Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter."

Although if your indices are not numerical and/or are not enumerable (say, from 231 to 324 inclusive), then you may be better off with, as Rocket says, array_fill_keys() or your regular foreach.

like image 31
Xunnamius Avatar answered Sep 21 '22 00:09

Xunnamius