Page 1 of 1

pop an item out of the middle of array

Posted: Sat Jun 16, 2007 5:23 am
by arukomp
Hi,

I have an array created by explode() function, so keys are basically 0, 1, 2, 3... And all array values are integers, like 1, 45, 12, 845...

I need to pop out an item which has a value of, for example, 12. Also, if there are multiple items with same value, only one of them should be poped out.

Code: Select all

$array = Array (
0 => 1,
1 => 12,
2 => 12,
3 => 45,
4 => 124 )

$item = 12;
// I need to delete one item with value $item from array $array
Thanks for any help

Posted: Sat Jun 16, 2007 6:44 am
by Gente
Pretty simple foreach. :) Or if don't like it maybe following will help you:

Code: Select all

<?php
$trans = array(0 => 1, 1 => 1, 2 => 12);
$value_to_remove = 1;
$trans_a = array_flip($trans);
if (isset($trans_a[$value_to_remove]))
{
	unset($trans[$trans_a[$value_to_remove]]);
}
print_r($trans);
?>

Posted: Sat Jun 16, 2007 9:19 am
by stereofrog

Code: Select all

array_splice($array, array_search($item, $array), 1);

Posted: Sat Jun 16, 2007 12:43 pm
by arukomp
stereofrog wrote:

Code: Select all

array_splice($array, array_search($item, $array), 1);
Thanks, your code worked just great :D