Jump to content

Array key-value pairs.


jacob1986

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