beginnerForPHP Posted April 11, 2022 Share Posted April 11, 2022 $test['0000'] = [2 =>'tes000']; $test['1111'] = [0=>'tes1', 1=>'tes11', 2 =>'tes111']; $test['2222'] = [0=>'tes2', 1=>'tes22', 2 =>'tes333']; How do i prefill the $test array with missing keys with value as 'NIL' to get the result as : $test['0000'] = [0=>'NIL', 1=>'NIL', 2 =>'tes000']; $test['1111'] = [0=>'tes1', 1=>'tes11', 2 =>'tes111']; $test['2222'] = [0=>'tes2', 1=>'tes22', 2 =>'tes333']; Quote Link to comment https://forums.phpfreaks.com/topic/314689-how-to-pre-fill-an-array-with-missings-keys/ Share on other sites More sharing options...
gw1500se Posted April 11, 2022 Share Posted April 11, 2022 Looks like you already did that. Perhaps you need to better explain what you are trying to do and post some actual code. Also, when you post code use the code icon (<>) in the top menu and specify PHP. Quote Link to comment https://forums.phpfreaks.com/topic/314689-how-to-pre-fill-an-array-with-missings-keys/#findComment-1595242 Share on other sites More sharing options...
Solution Barand Posted April 11, 2022 Solution Share Posted April 11, 2022 $test = [ '0000' => [2 =>'tes000'], '1111' => [0=>'tes1', 1=>'tes11', 2 =>'tes111'], '2222' => [0=>'tes2', 2 =>'tes333'] ] ; $test = array_map( function($v) { return array_replace(array_fill_keys(range(0,2), 'NIL'), $v); } , $test); echo '<pre>' . print_r($test, 1) . '</pre>'; giving Array ( [0000] => Array ( [0] => NIL [1] => NIL [2] => tes000 ) [1111] => Array ( [0] => tes1 [1] => tes11 [2] => tes111 ) [2222] => Array ( [0] => tes2 [1] => NIL [2] => tes333 ) ) 1 Quote Link to comment https://forums.phpfreaks.com/topic/314689-how-to-pre-fill-an-array-with-missings-keys/#findComment-1595244 Share on other sites More sharing options...
beginnerForPHP Posted April 15, 2022 Author Share Posted April 15, 2022 (edited) @BarandHow do i use the range() in case if my array is as follows with time range or is there any other alternative as time difference can be based on hour and half-hour. In example it is based on every hour. Edited April 15, 2022 by beginnerForPHP Quote Link to comment https://forums.phpfreaks.com/topic/314689-how-to-pre-fill-an-array-with-missings-keys/#findComment-1595353 Share on other sites More sharing options...
Barand Posted April 15, 2022 Share Posted April 15, 2022 Use a DatePeriod() object to generate the NIL array. I'd show the code but I am having difficulty processing that image of your data in my test code. (Hint: in future, use var_export() with arrays) Quote Link to comment https://forums.phpfreaks.com/topic/314689-how-to-pre-fill-an-array-with-missings-keys/#findComment-1595354 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.