PHP - Remove Unwanted Elements From Array -
let's have array following.
[0] => array [0] => peter drives 45km work [1] => tom rides 32km friends [2] => lisa walks 6km gym [3] => bob cycles 12km keep fit [4] => bill takes train 63km work [5] => penny runs 8km shop [6] => robert takes taxi 21km museum
suppose want keep people travelled between 10-15km , remove others array. also, suppose range want use variable, ie: today might see travelled between 10-15km, tomorrow might see travelled between 5-15km, next day might see travelled between 30-50km.
how go searching through array , either removing elements not fall within specified range, or moving elements require new array?
with regard elements require, need retain entire value, not distance travelled.
you can use php's array filter functions in combination callback uses regular expression extract relevant number strings:
<?php $min = 10; $max = 20; $input = [ "peter drives 45km work", "om rides 32km friends", "lisa walks 6km gym", "bob cycles 12km keep fit", "bill takes train 63km work", "penny runs 8km shop", "robert takes taxi 21km museum", ]; $output = array_filter($input, function($string) use ($min, $max) { preg_match('/([0-9]+)km/', $string, $matches); $number = intval($matches[1]); return ($number>$min) && ($number<$max); }); print_r($output);
the output of example (with given values $min
, $max
) is:
array ( [3] => bob cycles 12km keep fit )
different approaches possible, here used "closure" keep things compact. values in $min
, $max
ones want define in dynamic manner. error handling should added inside callback function in case input strings have unexpected format. left out here keep things compact again...
Comments
Post a Comment