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.

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?

index.php
<?php

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

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


//unset($colors[0]);
//unset($colors[2]);

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




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

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


var_dump ($colors);


?>

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
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[0]="Magenta";
$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