Sanooj T Sanooj T - 5 months ago 13
PHP Question

Array only contain numbers in php

Hi guys i have an array

$a=[1,2,3,4,5,...]


But i want to check if any other element than number exist in array
For example

These are my arrays

$a=[1,2,3,4,5,a,6,b,7]
$b=[1,2,3,4,5]


$a has numbers and variables

$b has numbers only

So my output is

check($a) should be false

check($b) should be true

Answer

is_numeric and simple foreach will be usful in this case.

Iterate over each element of array using foreach and check if the element is number or not using is_numeric() function.

Like this,

function check($array) {
     $allNumeric = true;
     foreach($array as $value) {
          if (!(is_numeric($key))) {
               $allNumeric = false;
               break;
          } 
     }
     return $allNumeric;
}

Just break the loop as soon as you hit the first non-numeric value and return the Boolean flag used in loop.

http://php.net/manual/en/function.is-numeric.php

http://php.net/manual/en/control-structures.foreach.php