Jump to content

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
)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.