Tuesday 23 July 2019

PHP How to delete from array between values




i want to remove from array by minimum and maximum values

for example i have the next array



['10','11','12','12.5','13','14','15.5','16']


i need to remove values from 12 to 13 to be



['10','11','14','15.5','16']



how can make it working in PHP ?
can any one help ? thanks in advance.


Answer



You can loop through the array and use unset to remove the values that meet your condition, like this:



$values = ['10','11','12','12.5','13','14','15.5','16'];
foreach ($values as $i => $value) {
if ($value >= 12 && $value <= 13) {
unset($values[$i]);

}
}

print_r($values);


The result:



Array
(

[0] => 10
[1] => 11
[5] => 14
[6] => 15.5
[7] => 16
)


You can also use array_filter function like this:




$values = ['10','11','12','12.5','13','14','15.5','16'];

$result = array_filter($values, function($value) {
return $value < 12 || $value > 13;
});

print_r($result);

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...