More Concise Way to Check to See If an Array Contains Only Numbers (Integers)

More concise way to check to see if an array contains only numbers (integers)

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

It would help you in the future to define two helper, higher-order functions:

/**
* Tell whether all members of $array validate the $predicate.
*
* all(array(1, 2, 3), 'is_int'); -> true
* all(array(1, 2, 'a'), 'is_int'); -> false
*/
function all($array, $predicate) {
return array_filter($array, $predicate) === $array;
}

/**
* Tell whether any member of $array validates the $predicate.
*
* any(array(1, 'a', 'b'), 'is_int'); -> true
* any(array('a', 'b', 'c'), 'is_int'); -> false
*/
function any($array, $predicate) {
return array_filter($array, $predicate) !== array();
}

Array only contain numbers in php

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

Check if an array contains (only) numeric values

Shortest solution, evals to true if and only if every item is (coercible to) a number:

!yourArray.some(isNaN)

Array only contain numbers in php

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

Check if array values are ints

I imagine you can never beat O(n) as all the elements need to be checked that they conform to the rule. The below checks each element once O(n) and removes it, if it is not an integer then does a simple comparison.

Still will have a slightly larger storage complexity however (needs to store the filtered array).

O(n) is a representation of complexity, in this case the complexity is n (the number of elements in the array) as each element must be looked at once.

If for example you wanted to multiple every number by every other number the complexity is approximately O(n^2) as for each element you must look at each other element (though this is a poor example)

See this guide for further information on Big O Notation as it is called

However try the below (adapted from previous question)

if($only_integers === array_filter($only_integers, 'is_int')); // true
if($letters === array_filter($letters, 'is_int')); // false

You could then do

/**
* Test array against provided filter
* testFilter(array(1, 2, 'a'), 'is_int'); -> false
*/
function testFilter($array, $test) {
return array_filter($array, $test) === $array;
}

Check if any number in the array is not a int

if($numbers == is_numeric($numbers) ... is not correct

use

if (is_numeric($numbers) && $total != null) {

The better function is ctype_digit

Please try this and do not use yours!

//$_POST['number'] = '1 2 3 4 5 6 7 8 9 10';
$notnumber = '<center>You must enter a number</center>';
$empty = '<center>The field is empty.</center>';

if(!isset($_POST['number']) || strlen($_POST['number']) <= 0){
echo $empty;
}
else{
if( !preg_match('/^([1-9]{1})([0-9]*)(\s)([0-9]+)/', $_POST['number']) ){
echo $notnumber;
}else{
$total = null;
$number = $_POST['number'];
$numbers = explode(" ", $number);
//remove after test
echo "<pre>";
print_r($numbers);
echo "</pre>";
//end remove
$total = array_sum($numbers);
//count(array) = number of elements inside $array
$avg = $total / count($numbers);
echo '<center>Avarge is: <b>'.$avg.'</b></center>';
}
}

Python check if list items are integers?

Try this:

mynewlist = [s for s in mylist if s.isdigit()]

From the docs:

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.


As noted in the comments, isdigit() returning True does not necessarily indicate that the string can be parsed as an int via the int() function, and it returning False does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.

Java String - See if a string contains only numbers and not letters

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){

to:

if (text.matches("[0-9]+") && text.length() > 2) {

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).



Related Topics



Leave a reply



Submit