jacob1986 Posted October 13, 2015 Share Posted October 13, 2015 I have an exercise which I must complete, but thus far... I'm a bit stuck and don't know if I have made the correct code array? Question: Start with the following code: $array = array ('2' => 1, 3); Without making a new array, change the above array so that the key-value pairs are: 2 => 1 3 => 3 b => 4 4 => 2 I don't think this code (as below) is correct because of the commas in the numbersequence... I'm guessing it should be 21, 33, b4, 42? <?php $array = array ('2' => 1, 3 => 3, b => 4, 4 => 2); foreach($array as $key=>$val) { echo" $key, $val"; } ?> Output: 2, 1 3, 3 b, 4 4, 2. Quote Link to comment https://forums.phpfreaks.com/topic/298570-array-key-value-pairs/ Share on other sites More sharing options...
ginerjm Posted October 13, 2015 Share Posted October 13, 2015 If you want: 21, 33, b4, 42 You need to output that: echo "$key$val, "; If you don't want that, I'm not sure what you are asking for. Quote Link to comment https://forums.phpfreaks.com/topic/298570-array-key-value-pairs/#findComment-1523170 Share on other sites More sharing options...
hansford Posted October 13, 2015 Share Posted October 13, 2015 $array = array('2' => 1, 3); // remove the last element array_pop($array); // add the remaining elements $array['3'] = 3; $array['b'] = 4; $array['4'] = 2; print_r($array); Output: Array ( [2] => 1 [3] => 3 [b] => 4 [4] => 2 ) Quote Link to comment https://forums.phpfreaks.com/topic/298570-array-key-value-pairs/#findComment-1523178 Share on other sites More sharing options...
Barand Posted October 13, 2015 Share Posted October 13, 2015 No need to pop any elements, the starting position is already Array ( [2] => 1 [3] => 3 ) since the numeric index will automatically increment after any provided numeric index. So all that is required is to add the final two elements $array['b'] = 4; $array[] = 2; // adds index 4 So, in full $array = array('2' => 1, 3); $array['b'] = 4; $array[] = 2; echo '<pre>',print_r($array, true),'</pre>'; //result Array ( [2] => 1 [3] => 3 [b] => 4 [4] => 2 ) 1 Quote Link to comment https://forums.phpfreaks.com/topic/298570-array-key-value-pairs/#findComment-1523187 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.