Difficulty checking if elements in array are type integer PHP

Daniel Mabinko picture Daniel Mabinko · May 2, 2012 · Viewed 11.7k times · Source


I am trying to detect if one or more variables contain numbers. I have tried a few different methods, but I have not been entirely successful.

Here is what I have tried.

<?php
$one = '1';
$two = '2';

$a1 = '3';
$a2 = '4';
$a3 = '5';


$string_detecting_array = array(); 

array_push($string_detecting_array, $one,$two,$a1,$a2,$a3); 

foreach ($string_detecting_array as $key) { 
    if (is_numeric($key)) {
        echo 'Yes all elements in array are type integer.';
    } 
    else {
        echo "Not all elements in array were type integer.";
    }
}

?>



I haven't been successful using this method. Any ideas? Thankyou in advance!

Answer

Jon picture Jon · May 2, 2012

First off, your loop logic is wrong: you should process all the items in the array before reaching a verdict. The shortest (although not most obvious) way to do this is with

$allNumbers = $array == array_filter($array, 'is_numeric');

This works because array_filter preserves keys and comparing arrays with == checks element counts, keys, and values (and the values here are primitives, so can be trivially compared).

A more mundane solution would be

$allNumbers = true;
foreach ($array as $item) {
    if (!is_numeric_($item)) {
        $allNumbers = false;
        break;
    }
}

// now $allNumbers is either true or false

Regarding the filter function: if you only want to allow the characters 0 to 9, you want to use ctype_digit, with the caveat that this will not allow a minus sign in front.

is_numeric will allow signs, but it will also allow floating point numbers and hexadecimals.

gettype will not work in this case because your array contains numeric strings, not numbers.