0

I have a foreach loop and I would like to completely remove the array elements that satisfy the criteria, and change the keys to stay sequential 1,2,3,4.

I have:

$thearray = array(20,1,15,12,3,6,93);
foreach($thearray as $key => $value){
    if($value < 10){
        unset($thearray[$key]);
    }
}
print_r($thearray);

But this keeps the keys as they were before. I want to make them 1,2,3,4, how can this be achieved?

2
  • This gives me: Array ( [0] => 20 [2] => 15 [3] => 12 [6] => 93 ) But I want the key to be 0,1,2,3 not 0,2,3,6... Commented Nov 2, 2012 at 16:47
  • Have you even tried to look that up in te php documentation, section Array functions? Commented Nov 2, 2012 at 16:48

3 Answers 3

5

Reset the array indices with array_values():

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

Comments

1

You can just use array_filter to remove the array elements that satisfy the criteria

 $thisarray = array_filter($thearray,function($v){ return $v > 10 ;});

Then use array_values change the keys to stay 0, 1,2,3,4 .... as required

  $thisarray = array_values($thisarray);

4 Comments

array_filter will keep the old indices.
What version of PHP are you using ??
Closures are supported from php version 5.3.0.
I think I do not have that sorry. I have now solved it with your help guys using array_values. problem solved. Thank you all.
0

Build up a new array and then assign that to your original array after:

$thearray=array(20,1,15,12,3,6,93);
$newarray=array();
foreach($thearray as $key=>$value){
  if($value>=10){
    $newarray[]=$value
  }
}
$thearray=$newarray;
print_r($thearray);

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.