0

Can I remove the first three elements and all the remaining ones where value is not equal to 2? The language is php.

print_r($array)

outputs

Array ( 
    [0] => Array ( [name] => aa [value] => 0 )        
    [1] => Array ( [name] => db [value] => 1 ) 
    [2] => Array ( [name] => bc [value] => 2 )
    [3] => Array ( [name] => ba [value] => 3 ) 
    [4] => Array ( [name] => ba [value] => 0 ) 
    [5] => Array ( [name] => bc [value] => 1 )    
    [6] => Array ( [name] => aa [value] => 2 ) 
    [7] => Array ( [name] => cb [value] => 3 )
    [8] => Array ( [name] => ca [value] => 0 ) 
    [9] => Array ( [name] => dc [value] => 1 ) 
    [10] => Array ( [name] => db [value] => 2 )
    [11] => Array ( [name] => aa [value] => 3 )
    [12] => Array ( [name] => dd [value] => 0 )
    [13] => Array ( [name] => db [value] => 1 )
    [14] => Array ( [name] => bb [value] => 2 )
    [15] => Array ( [name] => ac [value] => 3 )
) 

I also need to reindex so that it begins from 0

Array ( 
    [0] => Array ( [name] => aa [value] => 2 ) 
    [1] => Array ( [name] => db [value] => 2 )
    [2] => Array ( [name] => bb [value] => 2 )
) 
7
  • It would depend on the language. Commented Feb 9, 2015 at 19:08
  • Yes, but you'll have to write some code to do it. Try something and tell us how it goes, and if it doesn't work, then we can help. Commented Feb 9, 2015 at 19:21
  • Is it always the first three elements? Or just remove those that don't have a value of 2? Commented Feb 9, 2015 at 19:24
  • @JasonMcCreary Yes, the first three elements should always be destroyed no matter what, and from the fourth one only those which value is 2 should be kept. Commented Feb 9, 2015 at 19:26
  • @AndyLester. Thanks, I have tried to unset the elements with a foreach loop, but couldn't work it out how to unset more than one element at once. Commented Feb 9, 2015 at 19:28

1 Answer 1

3

You can do do it this way:

$new_array = array();

foreach ($array as $k => $v) {
    if ($k > 2 && $v['value'] == 2) {
        $new_array[] = $v;
    }
}

print_r($new_array);
Sign up to request clarification or add additional context in comments.

2 Comments

That will copy items where $v['value'] is equal to 2. If you want to remove those items (as I understand the question), it's !=
It's the other way around, I want to remove the values which are not equal to 2. I wasn't clear enough. You helped me to understand this really well. If value is buried deeper in parent array, if ($k > 2 and $v['parent'] ['value'] == 2) works as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.