Forum Moderators: coopster

Message Too Old, No Replies

Remove items from array, shift positions

         

briesm

3:17 pm on Jun 6, 2005 (gmt 0)

10+ Year Member



Hey, lets say I have
x = array("red", "blue", "green", "yellow", "orange", "grey");

Now lets say I have a loop that prints out what is in the array.
I want to be able to remove blue green and yellow, but effectively shift down everything else in the array (in this case orange and grey) so that orange is now positioned relative to where blue was and grey is where green was. By this I mean x[1] = "blue"
and x[2] now equals "grey". How can I do this?

Timotheos

3:54 pm on Jun 6, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Oh goodie another array problem.

$array = array("red", "blue", "green", "yellow", "orange", "grey");

unset ($array[1]);
unset ($array[2]);
unset ($array[3]);
array_unshift ($array, array_shift ($array));

This works but I'm sure coopster has a better way using array_merge. He'll be along shortly ;-)

mcibor

8:58 pm on Jun 6, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There's a better way, because you may not know where these strings are. Then use array_filter() [php.net...]

<?php
function my_colors($str){
if(in_array($str, array("blue", "green", "yellow"))) return false; else return true;
}

$output_array = array_merge(array(), array_filter($array, "my_colors"));
?>

This should work! If not, then coopster may have a word about it:)

Best regards
Michal Cibor

coopster

5:48 pm on Jun 7, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Bunch o' smart alecks -- now I know how jatar_k feels ;)

array_shift() [php.net] does exactly what you want. You will just have to do some comparison during your loop to determine whether or not you want to shift the element off the array or not. That's where the in_array() [php.net] will come in handy.

The fellas have thrown out a few options here so you'll have to read up on the different functions and see what is going to work best for you.

mincklerstraat

7:28 pm on Jun 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If you have a really huge array and you're often having to check whether there's a certain value or not, it might make sense to make your array like:
$colors = array('yellow' => 1, 'red' => 1, 'blue' => 1);
With honking big arrays, it can be faster to do:
if(isset($color['yellow'])) than if(in_array($colors, 'yellow')); (don't take my word on parameter order there).
Just a note for future work in arrays. You probably don't have thousands and thousands of colors.