Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if variable has a number php

Tags:

I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:

"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true

There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help.

like image 280
Scott Avatar asked May 23 '09 15:05

Scott


People also ask

How do you check if a string is a number in PHP?

To check if given string is a number or not, use PHP built-in function is_numeric(). is_numeric() takes string as an argument and returns true if the string is all numbers, else it returns false.

Is numeric or INT PHP?

The key difference between these two functions is that is_int() checks the type of variable, while is_numeric() checks the value of the variable. $var = "123"; $var is a string of numbers, not an integer value.

What is not numeric in PHP?

The is_numeric() function is an inbuilt function in PHP which is used to check whether a variable passed in function as a parameter is a number or a numeric string or not. The function returns a boolean value.

Is 0 an INT PHP?

PHP converts the string to an int, which is 0 (as it doesn't contain any number representation).


1 Answers

You can use the strcspn function:

if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
  echo "true";
else
  echo "false";

strcspn returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.

There is no need to invoke the regular expression engine for this.

like image 84
Martin Geisler Avatar answered Sep 28 '22 05:09

Martin Geisler