2

I have array:

Arrays:

Array
(
[0] => Array
    (
        [name] => point
        [visibility] => 
    )

[1] => Array
    (
        [name] => php_first_table
        [visibility] => 1
    )

[2] => Array
    (
        [name] => ohz
        [visibility] => 1
    )

)

Now i want to find and remove element with name=ohz:

    for($i=0;$i<count($arrays);$i++){
        if(array_search("ohz",$arrays[$i])){
            unset($arrays[$i]);
        }
    }
    print_r($arrays);

output:

Array
(
[0] => Array
    (
        [name] => point
        [visibility] => 
    )

[2] => Array
    (
        [name] => ohz
        [visibility] => 1
    )

)

Why php_first_table not ohz was deleted?

1
  • The code should work fine. Can you provide a complete program that has this behavior? Commented Oct 25, 2013 at 10:40

3 Answers 3

3

In PHP there is array_filter() for this:

$arrays = array_filter($arrays, function($item)
{
   return !(array_key_exists('name', $item) && $item['name']=='ohz');
});
Sign up to request clarification or add additional context in comments.

3 Comments

@Jon I'll check now, thank you (I'm messing this with something else?)
To be fair, changing the internal array pointer yourself (e.g. by calling reset inside the loop) is problematic. But deleting items is OK.
@Jon You're correct, I missed array pointer (which has nothing to do with this case, obviously). Sorry, better to take rest.. Thanks again!
2

Try like

for($i=0;$i<count($arrays);$i++){
    if($arrays[$i]['name'] == 'ohz')){
        unset($arrays[$i]);
    }
}
print_r($arrays);

Comments

0

Try this:

<?php
        $arr_var  = Array
        (
            Array('name' => 'point','visibility' => ''),
            Array('name' => 'php_first_table', 'visibility' => 1),
            Array('name' => 'ohz', 'visibility' => 1)
        );

        foreach($arr_var as $key => $value)
        {
            if($value['name'] == 'ohz'){
                unset($arr_var[$key]);
            }
        }

        echo '<pre>';
        print_r($arr_var);
        ?>

working fine.

  • Thanks

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.