Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
gabriel wambua5,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?
<?php $colors = array("Red","Green","Blue"); array_unshift ($colors, "Yellow"); array_push($colors, "Black"); array_splice ($colors, 1,3 array("Magenta","Cyan"); //unset($colors); //unset($colors); //$colors="Magenta"; //$colors ="Cyan"; //$replacement=array(0=>"Magenta", 3=>"Cyan"); //$final= array_replace($colors,$replacement); var_dump ($colors); ?>
Jennifer NordellTreehouse 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="Magenta"; $colors ="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!