preg_grep does not return the right results

76 Views Asked by At

The following code does not capture 45.00 as a result:

$array = array(50,45.00,34,56,6.67);
$fl_array = preg_grep("/^(\d+)?\.(\d)+$/", $array);

Any suggestion?

1

There are 1 best solutions below

0
On

If you do a var_dump($array); you will get:

array(5) {
  [0]=> int(50)
  [1]=> float(45)
  [2]=> int(34)
  [3]=> int(56)
  [4]=> float(6.67)
}

PHP you transform 45.00 into 45. That's why you can't find with the regex.

What you can do is to insert only strings.

$array = array("50","45.00","34","56","6.67");

Then it's going to work.

Another option is to filter only float numbers from the array:

$array = array(50,45.00,34,56,6.67);
$fl_array = array_filter($array, function($item) {
    return is_float($item);
});