Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Arrays and Control Structures PHP Arrays Modifying Arrays

Vladislav Mavrin
PLUS
Vladislav Mavrin
Courses Plus Student 3,125 Points

How do I replace several values from array?

Got stuck with this task 1) How do I remove several values from a certain key from an array?

For example in this code I have 5 keys and I need to replace 2nd and 4th, so I assume I should use array_splice function: array_splice ($colors, 2, 4, array("magenta", "cyan")); But this seems to be wrong

index.php
<?php

$colors = array("Red","Green","Blue");

//add modifications below this line
array_unshift($colors,"Yellow");
array_push($colors,"Black");
array_splice($colors

2 Answers

Simon Coates
Simon Coates
28,694 Points

I think what they're testing you on is that the array reindexes. So if you add to beginning, the subsequent value indices adjust by one. For task 2, it accepts:

<?php

$colors = array("Red","Green","Blue");

//add modifications below this line
array_unshift($colors,"Yellow");
array_push($colors,"Black");

$colors[1] = "Magenta"; // red was previously was at position 0
$colors[3] = "Cyan";