-1

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

Sanooj T
  • 1,317
  • 1
  • 14
  • 25

2 Answers2

5

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) {
     foreach($array as $value) {
          if (!is_numeric($value)) {
               return false;
          } 
     }
     return true;
}

Just return false as soon as you hit the first non-numeric.

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

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

Colandus
  • 1,634
  • 13
  • 21
Alok Patel
  • 7,842
  • 5
  • 31
  • 47
2

You should use PHP is_numeric() function. Iterate over your array and apply this function to check if values are numeric . A sample for such logic from PHP documentation page is given below .

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo "'{$element}' is numeric", PHP_EOL;
    } else {
        echo "'{$element}' is NOT numeric", PHP_EOL;
    }
}                    
j.Doe
  • 172
  • 12
Saurabh Chaturvedi
  • 2,028
  • 2
  • 18
  • 39