Home » Php » PHP: set all values in an array to something

PHP: set all values in an array to something

Posted by: admin April 23, 2020 Leave a comment

Questions:

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'

How to&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);

Answer:

array_fill_keys() should be what you need:

$keys = array_keys($yourArray);
$filled = array_fill_keys($keys, 1);

Answer:

For PHP >5.3 you can use anonymous functions.

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

Note: value is passed by reference.

Answer:

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.

Answer:

I got at this post with the same question but I ended up getting another aproach.

Why using array_flip + array_keys instead of simply use array_values?

$array = array(
    1 => 231,
    2 => 432,
    3 => 324
);

$array = array_fill_keys(array_values($array), 1);

Answer:

Any method that you call, such as array_map or fill_keys would still be using a loop to iterate over the array. It seems like you would want something such as array_map, which can be found here

If you consider that to be more elegant, to each his own:)

Answer:

array_replace(array_flip($columns), array_fill_keys($columns, 0));