34

How do you verify an array contains only values that are integers?

I'd like to be able to check an array and end up with a boolean value of true if the array contains only integers and false if there are any other characters in the array. I know I can loop through the array and check each element individually and return true or false depending on the presence of non-numeric data:

For example:

$only_integers = array(1,2,3,4,5,6,7,8,9,10);
$letters_and_numbers = array('a',1,'b',2,'c',3);

function arrayHasOnlyInts($array)
{
    foreach ($array as $value)
    {
        if (!is_int($value)) // there are several ways to do this
        {
             return false;
        }
    }
    return true;
}

$has_only_ints = arrayHasOnlyInts($only_integers ); // true
$has_only_ints = arrayHasOnlyInts($letters_and_numbers ); // false

But is there a more concise way to do this using native PHP functionality that I haven't thought of?

Note: For my current task I will only need to verify one dimensional arrays. But if there is a solution that works recursively I'd be appreciative to see that to.

3
  • Does it also work for non integers? array('1','2','3'); I'm not sure if form elements are sent as string.
    – Chazy Chaz
    Commented Mar 23, 2016 at 15:42
  • 1
    Just replace is_int with is_string
    – John Conde
    Commented Mar 23, 2016 at 15:44
  • Literally none of the answers given handle early termination. All those answers will walk the entire array even if the answer is already known after examining the first element. The built-in PHP functions for array traversal simply don't support early termination, full stop (pun intended). If you need early termination, you need to loop. Commented Sep 6, 2021 at 18:09

6 Answers 6

69
$only_integers       === array_filter($only_integers,       'is_int'); // true
$letters_and_numbers === array_filter($letters_and_numbers, 'is_int'); // false

It helps to define two helper, higher-order functions:

/**
 * Tell whether all members of $elems validate the $predicate.
 *
 * all(array(), 'is_int')           -> true
 * all(array(1, 2, 3),   'is_int'); -> true
 * all(array(1, 2, 'a'), 'is_int'); -> false
 */
function all($elems, $predicate) {
  foreach ($elems as $elem) {
    if (!call_user_func($predicate, $elem)) {
      return false;
    }
  }

  return true;
}

/**
 * Tell whether any member of $elems validates the $predicate.
 *
 * any(array(), 'is_int')               -> false
 * any(array('a', 'b', 'c'), 'is_int'); -> false
 * any(array(1, 'a', 'b'),   'is_int'); -> true
 */
function any($elems, $predicate) {
  foreach ($elems as $elem) {
    if (call_user_func($predicate, $elem)) {
      return true;
    }
  }

  return false;
}
12
  • Just want to make sure I'm not crazy here. Shouldn't $predicate, $array be reversed in array_filter()?
    – John Conde
    Commented Aug 24, 2010 at 18:51
  • @John you were right. I've used array_map quite a lot these days, hence the mistake. Commented Aug 24, 2010 at 18:55
  • Should be array_filter( array $input [, callback $callback ] ) Commented Oct 14, 2011 at 21:32
  • can you give an example on how to use the condition without the function because I can't get it to work :( thanks :) Commented Feb 15, 2013 at 15:55
  • 1
    "Any" means "some of" (more than zero) and not "not_all" implemented in the answear Commented Sep 27, 2016 at 6:27
6
 <?php
 $only_integers = array(1,2,3,4,5,6,7,8,9,10);
 $letters_and_numbers = array('a',1,'b',2,'c',3);

 function arrayHasOnlyInts($array){
    $test = implode('',$array);
    return is_numeric($test);
 }

 echo "numbers:". $has_only_ints = arrayHasOnlyInts($only_integers )."<br />"; // true
 echo "letters:". $has_only_ints = arrayHasOnlyInts($letters_and_numbers )."<br />"; // false
 echo 'goodbye';
 ?>
6
  • 3
    +1 for a simple solution, but this won't work with large arrays.
    – alexn
    Commented Aug 24, 2010 at 18:20
  • If the integer produced by implode() is larger then the server's max int value it will fail.
    – John Conde
    Commented Aug 24, 2010 at 19:24
  • you wouldn't happen to know what the default is would you ?
    – mcgrailm
    Commented Aug 24, 2010 at 19:27
  • 1
    @mcgrailm: I know this post is 4 years old, but it might help future visitors. It's PHP_INT_MAX. Commented Jan 27, 2014 at 17:49
  • @AmalMurali do you mean rather than is_numeric ?
    – mcgrailm
    Commented Jan 28, 2014 at 13:37
6

Another alternative, though probably slower than other solutions posted here:

function arrayHasOnlyInts($arr) {
   $nonints = preg_grep('/\D/', $arr); // returns array of elements with non-ints
   return(count($nonints) == 0); // if array has 0 elements, there's no non-ints
}
3
  • 1
    Works if the values are integers but of type string e.g. "123". You could simplify it to $only_integers === preg_grep('/\d/', $only_integers); // true as in @Ionut G. Stan's answer.
    – xofer
    Commented Mar 22, 2012 at 16:57
  • But only for positive integers. - sign can spoil the fun. Commented Sep 15, 2020 at 12:23
  • This also allows empty strings in the array.
    – Bloopy
    Commented Nov 28, 2021 at 11:09
5

There's always array_reduce():

array_reduce($array, function($a, $b) { return $a && is_int($b); }, true);

But I would favor the fastest solution (which is what you supplied) over the most concise.

9
  • Question is, how do you know which is the fastest without benchmarking? Commented Aug 24, 2010 at 18:21
  • the OP's code short-circuits the iteration by returning false if any of the elements are not integer. the rest of the solutions proposed iterates over the entire array.
    – bcosca
    Commented Aug 24, 2010 at 18:25
  • this solution returns true even when array passed is empty
    – bcosca
    Commented Aug 24, 2010 at 18:27
  • 1
    @konforce: var_dump(array_reduce(array(), function($a, $b) { return $a && is_int($b); }, true);) result: bool(true) that's due to the 3rd arg you provided.
    – bcosca
    Commented Aug 24, 2010 at 18:44
  • 2
    A quick benchmark with array with 1M integers records. foreach: 1.09s, reduce: 0.88s, for: 0.64s. After updating the 5th record to be non-integer... foreach: 0.59s, reduce: 0.54s, for: 0.0s. So to get optimal performance, replace the foreach with a for loop (and use a constant $c=count($array)). Your mileage may vary.
    – Matthew
    Commented Aug 24, 2010 at 18:49
5
function arrayHasOnlyInts($array) {
    return array_reduce(
        $array,
        function($result,$element) {
            return is_null($result) || $result && is_int($element);
        }
    );
}

returns true if array has only integers, false if at least one element is not an integer, and null if array is empty.

1
  • For PHP 8.2 with typing, the answer would be: php function arrayHasOnlyInts(array $array): bool { return array_reduce( $array, fn (?bool $result, mixed $value): bool => is_string($value) && ($result ?? true), ) ?? true; }
    – Biapy
    Commented Sep 29, 2023 at 11:46
0

Why don't we give a go to Exceptions?

Take any built in array function that accepts a user callback (array_filter(), array_walk(), even sorting functions like usort() etc.) and throw an Exception in the callback. E.g. for multidimensional arrays:

function arrayHasOnlyInts($array)
{
    if ( ! count($array)) {
        return false;
    }

    try {
        array_walk_recursive($array, function ($value) {
            if ( ! is_int($value)) {
                throw new InvalidArgumentException('Not int');
            }

            return true;
        });
    } catch (InvalidArgumentException $e) {
        return false;
    }

    return true;
}

It's certainly not the most concise, but a versatile way.

Not the answer you're looking for? Browse other questions tagged or ask your own question.