Jump to content

Set array values and preserve keys


Go to solution Solved by kicken,

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=[];});
Edited by NotionCommotion
Link to comment
https://forums.phpfreaks.com/topic/305537-set-array-values-and-preserve-keys/
Share on other sites

  • Solution

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), []);
  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.