PHP PHP Arrays and Control Structures PHP Arrays Modifying Arrays

gabriel wambua
gabriel wambua
5,058 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 Staff

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,058 Points

Thank you very much this solution worked brilliantly