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'
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.
The array_keys() function returns an array containing the keys.
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 .
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.
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);
array_fill_keys() should be what you need:
$keys = array_keys($yourArray); $filled = array_fill_keys($keys, 1);
For PHP >5.3 you can use anonymous functions.
array_walk($array,function(&$value){$value=1;});
Note: value is passed by reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With