I have an array, f. e.:
$arr = array(
4 => 'some value 1',
7 => 'some value 2',
9 => 'some value 3',
12 => 'some value 4',
13 => 'some value 5',
27 => 'some value 6',
41 => 'some value 7'
)
I need to create another array, where values will be array, but the keys will be the same; like this:
$arr = array(
4 => array(),
7 => array(),
9 => array(),
12 => array(),
13 => array(),
27 => array(),
41 => array()
)
Is there some build-in function in PHP for do that? array_keys()
didn't help me:
var_dump(array_keys($arr));
Returned:
array(7) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[4]=>
int(4)
[5]=>
int(5)
[6]=>
int(6)
}
Change Array Key using JSON encode/decode It's short but be careful while using it. Use only to change key when you're sure that your array doesn't contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.
If your arrays are not huge, you can use the push() method of the array to which you want to add values. The push() method can take multiple parameters so you can use the apply() method to pass the array to be pushed as a collection of function parameters. let newArray = []; newArray. push.
This is not possible - array keys must be strings or integers.
Try this . You can use array_fill_keys() for more info follow this link
$arr = array(
4 => 'some value 1',
7 => 'some value 2',
9 => 'some value 3',
12 => 'some value 4',
13 => 'some value 5',
27 => 'some value 6',
41 => 'some value 7'
);
$keys=array_keys($arr);
$filledArray=array_fill_keys($keys,array());
print_r($filledArray);
This should work for you:
Just array_combine()
your array_keys()
from the old array, with an array_fill()
'ed array full of empty arrays.
<?php
$newArray = array_combine(array_keys($arr), array_fill(0, count($arr), []));
print_r($newArray);
?>
output:
Array
(
[4] => Array ()
[7] => Array ()
[9] => Array ()
[12] => Array ()
[13] => Array ()
[27] => Array ()
[41] => Array ()
)
Change values to array saving keys:
$arr2 = array_map(function ($i){
return array();
}, $arr);
result
Array
(
[4] => Array ( )
[7] => Array ( )
[9] => Array ( )
[12] => Array ( )
[13] => Array ( )
[27] => Array ( )
[41] => Array ( )
)
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