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?

4

3 に答える 3

5

Reset the array indices with array_values():

$thearray = array_values( $thearray);
print_r($thearray);
于 2012-11-02T16:48:30.387 に答える
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);
于 2012-11-02T16:46:22.203 に答える
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);
于 2012-11-02T16:47:57.313 に答える