Jump to content

Set array values and preserve keys


NotionCommotion

Recommended Posts

How can I get [4=>[],5=>[],8=>[]] from $arr?  Guess I will just walk it, but thought there would be a more intuitive way to do so.  Not a big deal, but $arr is still needed so I will need to create a copy.  Thanks

$arr=[4=>[],5=>['a','b','c'],8=>[1,3,4]];
$arr1=array_fill_keys($arr,[]);
$arrCopy=$arr;
array_walk($arrCopy,function(&$v){$v=[];});
Link to comment
Share on other sites

Do you want to keep the keys, but reset all their values to empty array's? Not really sure what you're asking/trying to do.

 

If you just want the keys + empty array values then you could just do this:

$arr2 = array_fill_keys(array_keys($arr), []);
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.