php - How to skip iteration in foreach inside foreach -
i have array of values, , want insert values array if condition, if "if" true want skip iteration.
code:
$array=array(array(1=>11,2=>22,3=>23,4=>44,5=>55)); $insert=array(); foreach($array $k1=>$v1) { foreach($v1 $k2=>$v2) { if($v2==23) { break; } } $insert[]=$v1; }
final result should
array ( [0] => array ( [1] => 11 [2] => 22 [3] => 44 [4] => 55 ) )
i tried using: break,return,continue...
thanks
there few ways this. can loop on outer array , use array_filter on inner array remove value 23
(imo preferred; uses array of $dontwant
numbers easier add or change numbers later):
<?php $array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55)); $insert = array(); //array of numbers don't want $dontwant = array(23); //loop on outer array foreach($array $subarray){ //add $insert filtered array //subarray filtered remove value in $dontwant $insert[] = array_filter($subarray, function($val) uses ($dontwant) { //returns true if value not in array of numbers dont want return !in_array($val, $dontwant); }); } //display final array echo '<pre>'.print_r($insert,1).'</pre>';
or can reference first key add sub array in $insert
(which little more code trying , show not far off):
<?php $array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55)); $insert = array(); //loop on outer array foreach($array $k1=>$v1){ //add empty array $insert $insert[$k1] = array(); //loop on inner array foreach($v1 $k2=>$v2){ //if inner array value not 23 if($v2 != 23){ //add inner array in insert $insert[$k1][] = $v2; } } } //display result echo '<pre>'.print_r($insert,1).'</pre>';
both of these methods produce same result. imo using array_filter preferred method, second method might little easier understand new programming.
Comments
Post a Comment