13

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.

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206

7 Answers7

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
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

ctype_digit should be what you're looking for.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
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
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