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 Removing Array Elements

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

What array_values($learn); did exactly?

Alena didn't demonstrate how "resetting" the array works after all. I tried running the code but they keys inside the array remain the same - with spaces in between the numbers (0, 3, 4, 5, 7).

3 Answers

Sorry, I misunderstood.

If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

$array[9] = 'Pink';
$array[12] = 'Blue';
$array[5] = 'Red';

$array = array_values($array);

through this function you'll get this.

$array[0] = 'Pink';
$array[1] = 'Blue';
$array[2] = 'Red';

I hope this could help!

Steve Gallant
Steve Gallant
14,943 Points

Actually, just to be sure, wouldn't the new indexing be based on the relative order of the existing index keys? Resulting in:

$array[0] = 'Red';
$array[1] = 'Pink';
$array[2] = 'Blue';

thanks!

Hey Arikaturika,

array_values --> Outputs all values of an array. Do you want to reset the whole array or just single values? You can use unset for individual values. For example, to delete the second value you can do this.

unset ($learn[1]);

Best regards Phil

Arikaturika Tumojenko
Arikaturika Tumojenko
8,897 Points

Hey, Philipp. I was actually talking about array_values, not unset. As far as I remember, Alena was saying that array_values resets the order of the keys inside an array?

Arikaturika Tumojenko,

When you use the function it will reset the order of the indexes or 'refreshes' the array as Alena mentioned.

In the example above, unset will remove an element and its index from the array and leave a gap in the indexes. The array_values method will resolve the gap if that is what you need.