Jump to content

Recommended Posts

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 number
sequence... 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.
Link to comment
https://forums.phpfreaks.com/topic/298570-array-key-value-pairs/
Share on other sites

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