is_int Function returns string In PHP

时间:2018-02-03 11:08:19

标签: php

I am using is_int function To check Whether The Value i get is int or not My code is

<?php

$a = 3;

if(is_int($a)){
    echo "INT";
}else{
    echo "STRINIG";
}

Which returns me INT But When it tried Using This code

<?php

$a = "3";

if(is_int($a)){
    echo "INT";
}else{
    echo "STRINIG";
}

It returns me sting .

So why this happen ?

UPDATE

I have problem in following code Let Suppose i have array As

Array ( [0] => 4 [1] => xxxx )

now i have to fetch String So i do

foreach ($mypreferdservice as $value) {
  if(is_int($value)){
    echo "Int<br>";
  }else{
    echo "String";
  }
}

So it returns me string So How to solve this problem

3 个答案:

答案 0 :(得分:3)

If you want check if the value is numeric, then is_numeric(http://php.net/manual/en/function.is-numeric.php) may be what your after -

$a = "3";

if(is_int($a)){
    echo "INT";
}else{
    echo "STRINIG";
}
if(is_numeric($a)){
    echo "INT";
}else{
    echo "STRINIG";
}

is_int checks the type of a field, is_numeric checks the value.

This outputs (not formatted very well)...

STRINIGINT

答案 1 :(得分:0)

Anything surrounded by " or ' is string typed. That's why is_int function returning false.

The simplest way to specify a string is to enclose it in single quotes (the character ').

If the string is enclosed in double-quotes ("), PHP will interpret the following escape sequences for special characters:

php.net wiki on string type

To get an idea how php data types work, read on php data types

答案 2 :(得分:-1)

如果你想检查一个字符串是否是一个整数,那么单独is_intis_numeric就不会删除它:

function is_integer_numeric($string) {
           return is_numeric($string) && is_int($string + 0); // Adding 0 to a numeric will cast it to either a float or int depending on what it really is.
}


var_dump(is_integer_numeric(3)); // true 
var_dump(is_integer_numeric("3")); // true
var_dump(is_integer_numeric("3.1")); // false
var_dump(is_integer_numeric(3.1));  // false
var_dump(is_integer_numeric("test"));  // false