Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difficulty checking if elements in array are type integer PHP


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!

like image 860
Daniel Mabinko Avatar asked May 02 '12 16:05

Daniel Mabinko


People also ask

What is the use of Is_array () function?

The is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.

How do you check if an element is in an array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do you check if something is an integer in PHP?

The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.

How check array is associative or not in PHP?

How to check if PHP array is associative or sequential? There is no inbuilt method in PHP to know the type of array. If the sequential array contains n elements then their index lies between 0 to (n-1). So find the array key value and check if it exist in 0 to (n-1) then it is sequential otherwise associative array.


1 Answers

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.

like image 159
Jon Avatar answered Sep 30 '22 16:09

Jon