# Array key-value pairs.

## 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.`
##### Share on other sites

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.

##### Share on other sites

```\$array = array('2' => 1, 3);

// remove the last element
array_pop(\$array);
\$array['3'] = 3;
\$array['b'] = 4;
\$array['4'] = 2;

print_r(\$array);
```

Output:

```Array (  => 1  => 3 [b] => 4  => 2 )
```
##### Share on other sites

No need to pop any elements, the starting position is already

```Array
(
 => 1
 => 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
(
 => 1
 => 3
[b] => 4
 => 2
)
```

#### Archived

This topic is now archived and is closed to further replies.

×

• #### Activity

• Chat
×
• Create New...