Jump to content

Deleting a single item from the middle of an array?


jolyon_russ

Recommended Posts

I should probably be posting this in the OOP section but my problem is only half OOP related.

 

I have an array that contain objects, I want to be able to test against the id of that object and remove it from the array.

 

In it's simplest for I want to go from this:

 

$people = array('Tom', 'Dick', 'Harriet', 'Brenda', 'Jo');

 

...to this...

 

$people = array('Tom', 'Dick', 'Brenda', 'Jo');

 

The fact that the items in the array are objects should not matter right? Plus I've already written my loops and conditionals to check which item i need to remove.

 

function removeItem ( $item ) {

$len = count ( $_SESSION['basket_arr'] ) ;

if ( $len == 1 ) {

emptyBasket ( ) ;

} else {

for ( $i = 0 ; $i < $len ; $i++ ) {

if ( $item->id == $_SESSION['basket_arr'][$i]->id ) {

//$_SESSION['basket_arr'][$i] must go

}

}

}

}

 

Thanks in advance for your help.

 

 

Jolyon

I think you can use unset to delete a single array node similar to how you do with a variable, and what you could do is simply find the key based on the value (Read up on array functions to get it exactly) and then unset($array[$deltekey]) or if it sa bunch of them say foreach($deletekey as $value)

Cheers guys,

 

I did try unset already, but it screwed with my indexing:

 

$people = array([0] => 'Tom', [1] => 'Dick', [2] => 'Harriet', [3] => 'Brenda', [4] => 'Jo');

 

became...

 

$people = array([0] => 'Tom', [1] => 'Dick', [3] => 'Brenda', [4] => 'Jo');

 

If I do use unset is there a way that I can then, re-index the array to fill the gap? I know that array_splice does this automatically unless specified.

 

Thanks again for the help.

 

 

Jolyon

<?php
$people = array(0 => 'Tom', 1 => 'Dick', 2 => 'Harriet', 3 => 'Brenda', 4 => 'Jo');

unset ($people[2]);

$people = array_values($people);

echo '<pre>', print_r($people, true), '</pre>';
?>

-->
Array
(
    [0] => Tom
    [1] => Dick
    [2] => Brenda
    [3] => Jo
)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.