Jump to content

finding and unseting an element in array


keevitaja

Recommended Posts

$test = array('yks', 'kaks', 'kolm');
$key = array_shift((array_keys($test, 'kolm')));
echo '<br>';
unset($test[$key]);
print_r($test);

 

is it possible to write this shorter? i need to eliminate the 'kolm' from $test array!

 

actualy i have an array which contains objects

 

Array
(
    [0] => Page Object
        (
            [id] => 22
            [language_id] => 1
            [level] => 0
            [order_number] => 1
            [name] => 1
            [body] => 
        )

    [1] => Page Object
        (
            [id] => 23
            [language_id] => 1
            [level] => 1
            [order_number] => 2
            [name] => 2
            [body] => 
        )
)

 

i need to find the key where object Page->id has a value 23. can i do it?

 

You could use..

 

$test = array('yks', 'kolm', 'kaks');
$key = array_search('kolm', $test);
unset($test[$key]);

 

You'll need to check that $key !== false, as if it does currently it'll remove the element at key '0' (remember 0 == false, but 0 !== false).

 

ram4nd, your suggestion would only work assuming he knows the key value of 'kolm'. Also in_array() only returns a bool value, so he wouldn't be able to use it to identify the key if he didn't.

this how i do it now:

 

foreach($pages_array as $page_object) {
  if($page_object->id != $page->id) {
    $pages[] = $page_object; 
  }
}

 

where $pages_array is the array displayd in the first post and $page-id is the one i want to delete from array!

 

 

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.