I have an array in PHP with some variables for example (1,2,3,4,5,6,7) I want to get two separate arrays one with all the variables lower than $idusuario
(which might be 2, for example), for example the array 1
would have only one value "1" and array 2
would have "3,4,5,6,7".
PS: My php variables are:
$arrayfinal[] --> the array I want to divide
$idusuario --> the variable which separates both arrays
Easily:
$lessThan = array();
$greaterThan = array();
foreach($arrayFinal as $element){ // loop initial array
if($element < $idusuario){ // if element < idusuario, add to first array
$lessThan[] = $element;
}else{
$greaterThan[] = $element; // add to second array
Exclude and remove $idusuario
$lessThan = array();
$greaterThan = array();
foreach($arrayFinal as $element){ // loop initial array
if($element < $idusuario){ // if element < idusuario, add to first array
$lessThan[] = $element;
}elseif($element > $idusuario){
$greaterThan[] = $element; // add to second array
}
}
Another approach could be using array_filter
instead of foreach
:
$smaller = array_filter($array, function($value) use ($separator) {
return $value < $separator;
});
$bigger = array_filter($array, function($value) use ($separator) {
return $value > $separator;
});
But I'd guess the foreach
approach is faster.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.