For instance, "000", "404", and "0523" can be converted into whole numbers in PHP, but "42sW" and "423 2343" cannot be converted into whole numbers.
Asked
Active
Viewed 8,278 times
13
-
Are you looking for something more than just checking that every character in the string is a digit? – John3136 Feb 24 '12 at 04:09
-
1[Which definition of whole number](https://en.wikipedia.org/wiki/Whole_number) are you thinking of? – icktoofay Feb 24 '12 at 04:11
7 Answers
21
Use the ctype_digit
function. is_numeric
will also permit floating point values.
$numArray = array("1.23","156", "143", "1w");
foreach($numArray as $num)
{
if (ctype_digit($num)) {
// Your Convert logic
} else {
// Do not convert print error message
}
}
}

Ken Wayne VanderLinde
- 18,915
- 3
- 47
- 72

Naveen Kumar
- 4,543
- 1
- 18
- 36
-
Thanks, `ctype_digit` works great. `is_numeric` doesn't work since all rational numbers will work for is_numeric, but it's nice to know that function too, thanks! – dangerChihuahua007 Feb 24 '12 at 18:32
-
-
1If you do pass in int it will return false regardless if its a whole number. That may not be expected. Thought it worth mentioning, cheers. – gus Mar 05 '12 at 10:05
-
1$numArray = array("1.23",156, "143", "1w"); 1.23 false *156 false* 143 true 1w false – gus Mar 05 '12 at 14:48
-
@David Faux: 1.2e2 is a "whole number" but will will fail the ctype,_digit() test. – symcbean Aug 08 '17 at 22:36
9
PHP's is_numeric()
can determine if a given param is a number or a number string. Have a read through the manual for some examples.

Russell Dias
- 70,980
- 5
- 54
- 71
2
42Sw can be converted to a number by using intval()
echo intval("42sW"); // prints 42

gus
- 765
- 3
- 14
- 26
1
use is_numeric()
:
if (is_numeric("string")) {
echo "This can be converted to a number";
}

fardjad
- 20,031
- 6
- 53
- 68
-
1
-
-
@clockw0rk depending on the use case it might be ok or not. I did have once a case where I specifically needed to determine if a string is integer. – galdikas Jun 15 '23 at 12:05
0
You could try something like this.
<?php
if (is_numeric($string)) {
//functions here
}
else{
//functions2 here
}
?>

ionFish
- 1,004
- 1
- 8
- 20
0
$test = "42sW";
if (ctype_digit($test)) {
echo "The string $test consists of all digits.\n";
} else {
echo "The string $test does not consist of all digits.\n";
}
//OR
is_numeric($test); // false

Sudhir Bastakoti
- 99,167
- 15
- 158
- 162
-
1Wouldn't `is_numeric()` return true for non-whole numbers as well (1.23)? – jprofitt Feb 24 '12 at 04:20