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!
You can use gettype
if you want to explicitly know if the variable is a number. Using is_numeric
will not respect types.
If you are intending to use is_numeric
but want to know if all elements are, then proceed as follows:
$all_numeric = true;
foreach ($string_detecting_array as $key) {
if (!(is_numeric($key))) {
$all_numeric = false;
break;
}
}
if ($all_numeric) {
echo 'Yes all elements in array are type integer.';
}
else {
echo "Not all elements in array were type integer.";
}