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

gabriel wambua
gabriel wambua
5,061 Points

Hi everyone, I need help with replacing array items

I thought that the array_splice element would work on this...what am i doing wrong?


$colors = array("Red","Green","Blue");
array_unshift ($colors, "Yellow");
array_push($colors, "Black");

array_splice ($colors, 1,3 array("Magenta","Cyan");


//$colors[2] ="Cyan";

//$replacement=array(0=>"Magenta", 3=>"Cyan");

//$final= array_replace($colors,$replacement);

var_dump ($colors);


1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there, gabriel wambua ! The array_splice will not work here as you would need two consecutive elements and these are separated by "Green".

However, your initial instinct and commented out code here, was almost spot on:

$colors[2] ="Cyan";

The above code is terribly close, but remember, that the array has been altered. It now contains["Yellow", "Red", "Green", "Blue", "Black"]. So "Red" is no longer at the index of 0, it's at the index of 1. And "Blue" is now at the index of 3 instead of 2. Everything got moved over one when we added "Yellow" to the front of the list.

Hope this helps! :sparkles:

gabriel wambua
gabriel wambua
5,061 Points

Thank you very much this solution worked brilliantly