pop an item out of the middle of array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
arukomp
Forum Contributor
Posts: 113
Joined: Sun Sep 24, 2006 4:22 am

pop an item out of the middle of array

Post 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
User avatar
Gente
Forum Contributor
Posts: 252
Joined: Wed Jun 13, 2007 9:43 am
Location: Ukraine, Kharkov
Contact:

Post 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);
?>
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

Code: Select all

array_splice($array, array_search($item, $array), 1);
arukomp
Forum Contributor
Posts: 113
Joined: Sun Sep 24, 2006 4:22 am

Post by arukomp »

stereofrog wrote:

Code: Select all

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