Php переменная только числа

ctype_digit

Проверяет, являются ли все символы в строке text цифровыми.

Список параметров

Замечание:

Если передано целое число ( int ) в диапазоне между -128 и 255 включительно, то оно будет обработано как ASCII-код одного символа (к отрицательным значениям будет прибавлено 256 для возможности представления символов из расширенного диапазона ASCII). Любое другое целое число будет обработано как строка, содержащая десятичные цифры этого числа.

Начиная с PHP 8.1.0, передача нестроковых аргументов устарела. В будущем аргумент будет интерпретироваться как строка вместо кода ASCII. В зависимости от предполагаемого поведения аргумент должен быть приведён к строке ( string ) или должен быть сделан явный вызов функции chr() .

Возвращаемые значения

Возвращает true , если каждый символ строки text является десятичной цифрой, либо false в противном случае. При вызове с пустой строкой результатом всегда будет false .

Примеры

Пример #1 Пример использования ctype_digit()

$strings = array( ‘1820.20’ , ‘10002’ , ‘wsl!12’ );
foreach ( $strings as $testcase ) if ( ctype_digit ( $testcase )) echo «Строка $testcase состоит только из цифр.\n» ;
> else echo «Строка $testcase не состоит только из цифр.\n» ;
>
>
?>

Результат выполнения данного примера:

Строка 1820.20 не состоит только из цифр. Строка 10002 состоит только из цифр. Строка wsl!12 не состоит только из цифр.

Пример #2 Пример использования ctype_digit() со сравнением строк и целых чисел

$numeric_string = ’42’ ;
$integer = 42 ;

ctype_digit ( $numeric_string ); // true
ctype_digit ( $integer ); // false (ASCII 42 — это символ *)

is_numeric ( $numeric_string ); // true
is_numeric ( $integer ); // true
?>

Смотрите также

  • ctype_alnum() — Проверяет наличие буквенно-цифровых символов
  • ctype_xdigit() — Проверяет наличие шестнадцатеричных цифр
  • is_numeric() — Проверяет, является ли переменная числом или строкой, содержащей число
  • is_int() — Проверяет, является ли переменная целым числом
  • is_string() — Проверяет, является ли переменная строкой

User Contributed Notes 14 notes

All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: «123»).
3. ctype_digit() excepts all numbers to be strings (like: «123») and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

My function only accepts numbers regardless whether they are in string or in integer format.
/**
* Check input for existing only of digits (numbers)
* @author Tim Boormans
* @param $digit
* @return bool
*/
function is_digit ( $digit ) if( is_int ( $digit )) return true ;
> elseif( is_string ( $digit )) return ctype_digit ( $digit );
> else // booleans, floats and others
return false ;
>
>
?>

Читайте также:  Python numpy array slice

Please note that ctype_digit() will say true for strings such as ‘00001’, which are not technically valid representations of integers, while saying false to strings such as ‘-1’, which are. It’s basically a faster version of the regex /^\d+$/. As the name says, it answers the question «does this string contain only digits» literally. It does not answer «is this a valid representation of an integer». If that’s what you want, use is_int(filter_var($val, FILTER_VALIDATE_INT)) instead.

I just wanted to clarify a flaw in the function is_digit() suggested by «info at directwebsolutions dot nl » ..
It returns true in case of negative integers and false in case of strings that contain negative integers .
example:
is_digit(-10); // returns ture
is_digit(‘-10’); // returns false

Interesting to note that you must pass a STRING to this function, other values won’t be typecasted (I figured it would even though above explicitly says string $text).

$val = 42 ; //Answer to life
$x = ctype_digit ( $val );
?>

Will return false, even though, when typecasted to string, it would be true.

$val = ’42’ ;
$x = ctype_digit ( $val );
?>

Returns True.

$val = 42 ;
$x = ctype_digit ((string) $val );
?>

Which will also return true, as it should.

ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII ‘0’-‘9’) and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)

Источник

Php переменная только числа

Cast a string to binary using PHP < 5.2.1

I found it tricky to check if a posted value was an integer.

is_int ( $_POST [ ‘a’ ] ); //false
is_int ( intval ( «anything» ) ); //always true
?>

A method I use for checking if a string represents an integer value.

$foo [ ‘ten’ ] = 10 ; // $foo[‘ten’] is an array holding an integer at key «ten»
$str = » $foo [ ‘ten’]» ; // throws T_ENCAPSED_AND_WHITESPACE error
$str = » $foo [ ten ] » ; // works because constants are skipped in quotes
$fst = (string) $foo [ ‘ten’ ]; // works with clear intention
?>

It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

$hello = ‘Hello world’ ;
print $hello ;
unset( $hello );

$hello = ‘Hello world’ ;
$hello = (unset) print $hello ;

?>

Hoorah, we lost another line!

It would be useful to know the precedence (for lack of a better word) for type juggling. This entry currently explains that «if either operand is a float, then both operands are evaluated as floats, and the result will be a float» but could (and I think should) provide a hierarchy that indicates, for instance, «between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins» and so on (and don’t count on my example accurately capturing the true hierarchy, as I haven’t actually done the tests to figure it out). Thanks!

Читайте также:  Html list for links

May be expected, but not stated ..
Casting to the existing (same) type has no effect.
$t = ‘abc’; // string ‘abc’
$u=(array) $t; // array 0 => string ‘abc’ $v=(array) $u; // array 0 => string ‘abc’

Correct me if I’m wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what’s really happening:

class MyObject /**
* @param MyObject $object
* @return MyObject
*/
static public function cast ( MyObject $object ) return $object ;
>
/** Does nothing */
function f () <>
>

class X extends MyObject /** Throws exception */
function f () < throw new exception (); >
>

$x = MyObject :: cast (new X );
$x -> f (); // Your IDE tells ‘f() Does nothing’
?>

However, when you run the script, you will get an exception.

In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes. It also makes use of some regular expression matching rather than string position, replacing, etc. It takes an object ($obj) of any type and casts it to an new type ($class_type). Note that the new class type must exist:

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin’ less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
class Point protected $x , $y ;

public function __construct ( $xVal = 0 , $yVal = 0 ) $this -> x = $xVal ;
$this -> y = $yVal ;
>
public function getX () < return $this ->x ; >
public function getY () < return $this ->y ; >
>

$p = new Point ( 25 , 35 );
echo $p -> getX (); // 25
echo $p -> getY (); // 35
?>
Ok, now we need extra powers. PHP gives us several options:
A. We can tag on extra properties on-the-fly using everyday PHP syntax.
$p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it’s on a per-instance basis, blah.
B. We can try type-casting it to a different type to access more functions.
$p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with. and just like above, this only works on a per-instance basis.
C. Do it the right way using OOP — and just extend the Point class already.
class Point3D extends Point protected $z ; // add extra properties.

Читайте также:  line-height

public function __construct ( $xVal = 0 , $yVal = 0 , $zVal = 0 ) parent :: __construct ( $xVal , $yVal );
$this -> z = $zVal ;
>
public function getZ () < return $this ->z ; > // add extra functions.
>

$p3d = new Point3D ( 25 , 35 , 45 ); // more data, more functions, more everything.
echo $p3d -> getX (); // 25
echo $p3d -> getY (); // 35
echo $p3d -> getZ (); // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any «single lesser object» on-the-fly, and it’s way easier to do.

Re: the typecasting between classes post below. fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem. SO here’s a simple fix:

function typecast($old_object, $new_classname) if(class_exists($new_classname)) // Example serialized object segment
// O:5:»field»:9: $old_serialized_prefix = «O:».strlen(get_class($old_object));
$old_serialized_prefix .= «:\»».get_class($old_object).»\»:»;

$old_serialized_object = serialize($old_object);
$new_serialized_object = ‘O:’.strlen($new_classname).’:»‘.$new_classname . ‘»:’;
$new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
return unserialize($new_serialized_object);
>
else
return false;
>

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. 😉

If you have a boolean, performing increments on it won’t do anything despite it being 1. This is a case where you have to use a cast.

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.

Checking for strings to be integers?
How about if a string is a float?

/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt = preg_match ( ‘/^\s*(4+)\s*$/’ , $myString , $myInt );

echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes: ‘ . $myInt [ 1 ] : ‘No’ , «\n» ;

/* checks if a string is an integer with no whitespace before or after */
$isInt = preg_match ( ‘/^4+$/’ , $myString );

echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes’ : ‘No’ , «\n» ;

/* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
2+(\.5+)?
with
8+\.1+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*(2+(\.1+)?)\s*$/’ , $myString , $myNum );

echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes: ‘ . $myNum [ 1 ] : ‘No’ , «\n» ;

/* checks if a string is a float with no whitespace before or after */
$isInt = preg_match ( ‘/^2+(\.5+)?$/’ , $myString );

echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes’ : ‘No’ , «\n» ;

Источник

Оцените статью