I am posting numeric value by a form and in php file use var_dump(is_int($my_var)); but it return bool(false) though i am posting 1 and if I use var_dump(is_int(1)); it is fine and return bool(true)
what is wrong....?
Variables transmitted by a POST request are strings, so you're calling is_int() on a string which returns false.
You may use is_numeric() or filter_var() instead or simply cast your variable to an integer.
// First check if it's a numeric value as either a string or number
if(is_numeric($int) === TRUE){
// It's a number, but it has to be an integer
if((int)$int == $int){
return TRUE;
// It's a number, but not an integer, so we fail
}else{
return FALSE;
}
// Not a number
}else{
return FALSE;
}
Also, instead of getting the variable as
$my_var = $_POST["value"];
try this instead to see if the value is really passed.
$my_var = $_REQUEST["value"];
Related
Hi I am quite new in PHP and I wanna know how can I check what type of variable the user entered
For example if the user entered a string return an error.Or if the user entered an integer redirect him to the next html page.
I think you got what I mean.Please help me :-)
gettype
is_numeric
be aware:
var_dump(gettype('1')); // string
because
'1' !== 1
Take a look at filter_var. It allows you to test your input as you're describing.
Example assuming that you want to validate it's an int value:
<?php
$input = 'some string';
if (filter_var($input, FILTER_VALIDATE_INT) === false) {
// it's not an int value, return error
}
Try this
$type = gettype($input);
if($type == 'integer'){
// redirect
}
else{
echo "error";
}
The gettype() function is used to get the type of a variable. for more info read http://www.w3resource.com/php/function-reference/gettype.php
but i suggest use is_numeric() instead of gettype()
$type = is_numeric($input);
if($type){
// redirect
}
else{
echo "error";
}
because gettype treats variable in single quotes or double quotes as string so for gettype '1' is string not integer
Oh so ok i used the (is_numeric();)function and it worked thanks to all of you !! :DD
Im currently testing a simple PHP function.
I want to to return the currently value of a field if the function is called without any parameter passed or set a new value if a parameter is passed.
Strange thing is: if I pass 0 (var_dump is showing correct value int(1) 0), the function goes into the if branch like i called the function without any value and i just don't get why.
function:
public function u_strasse($u_strasse = 'asdjfklhqwef'){
if($u_strasse == 'asdjfklhqwef'){
return $this->u_strasse;
} else {
// set new value here
}
}
either u_strasse() or u_strasse(0) gets me in the if branch.
You should use null as the default value:
public function u_strasse($u_strasse = null)
{
if ($u_strasse === null) { $u_strasse = 'asdjfklhqwef'; }
// rest of function
}
When comparing variables of different types (specifically strings and numbers), both values will be converted to a number. Therefore, your 'asdjfklhqwef' converts to 0 (number), the comparison is true.
http://www.php.net/manual/en/language.operators.comparison.php
Use === instead of ==:
public function u_strasse($u_strasse = 'asdjfklhqwef'){
if($u_strasse === 'asdjfklhqwef'){
return $this->u_strasse;
} else {
// set new value here
}
}
In case of == php tries to convert 'asdjfklhqwef' to number (because you pass $u_strasse as a number) and (int)'asdjfklhqwef' equals 0. To avoid this behavior you need to compare strictly (===)
Read more about difference in == and === here
Pass '0' instead of 0. The former will be a string.
You can cast it like this:
$myvar = 0;
u_strasse((string)$myvar);
This question already has answers here:
How to check whether an array is empty using PHP?
(24 answers)
Closed 7 years ago.
I have the following code
<?php
$error = array();
$error['something'] = false;
$error['somethingelse'] = false;
if (!empty($error))
{
echo 'Error';
}
else
{
echo 'No errors';
}
?>
However, empty($error) still returns true, even though nothing is set.
What's not right?
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter() function's default behavior will remove all values from array which are equal to null, 0, '' or false.
Otherwise in your particular case empty() construct will always return true if there is at least one element even with "empty" value.
You can also check it by doing.
if(count($array) > 0)
{
echo 'Error';
}
else
{
echo 'No Error';
}
Try to check it's size with sizeof if 0 no elements.
PHP's built-in empty() function checks to see whether the variable is empty, null, false, or a representation of zero. It doesn't return true just because the value associated with an array entry is false, in this case the array has actual elements in it and that's all that's evaluated.
If you'd like to check whether a particular error condition is set to true in an associative array, you can use the array_keys() function to filter the keys that have their value set to true.
$set_errors = array_keys( $errors, true );
You can then use the empty() function to check whether this array is empty, simultaneously telling you whether there are errors and also which errors have occurred.
array with zero elements converts to false
http://php.net/manual/en/language.types.boolean.php
However, empty($error) still returns true, even though nothing is set.
That's not how empty() works. According to the manual, it will return true on an empty array only. Anything else wouldn't make sense.
From the PHP-documentation:
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
function empty() does not work for testing empty arrays!
example:
$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true
a function is necessary:
function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}
ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.
bye
(sorry for my english)
hi array is one object so it null type or blank
<?php
if($error!=null)
echo "array is blank or null or not array";
//OR
if(!empty($error))
echo "array is blank or null or not array";
//OR
if(is_array($error))
echo "array is blank or null or not array";
?>
I can't replicate that (php 5.3.6):
php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)
php > $error = array();
php > var_dump(empty($error));
bool(true)
php >
exactly where are you doing the empty() call that returns true?
<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>
In PHP, even if the individual items within an array or properties of an object are empty, the array or object will not evaluate to empty using the empty($subject) function. In other words, cobbling together a bunch of data that individually tests as "empty" creates a composite that is non-empty.
Use the following PHP function to determine if the items in an array or properties of an object are empty:
function functionallyEmpty($o)
{
if (empty($o)) return true;
else if (is_numeric($o)) return false;
else if (is_string($o)) return !strlen(trim($o));
else if (is_object($o)) return functionallyEmpty((array)$o);
// If it's an array!
foreach($o as $element)
if (functionallyEmpty($element)) continue;
else return false;
// all good.
return true;
}
Example Usage:
$subject = array('', '', '');
empty($subject); // returns false
functionallyEmpty($subject); // returns true
class $Subject {
a => '',
b => array()
}
$theSubject = new Subject();
empty($theSubject); // returns false
functionallyEmpty($theSubject); // returns true
Here is my code:
<?php
$id = $_GET["id"];
if (is_int($id) === FALSE) {
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
?>
It always enters inside the if.
is_int checks that the data type is an integer, but everything in $_GET will be a string. Therefore, it will always return false.
In a pinch, you could cast to an integer and then check for != 0.
$id = isset($_GET['id']) ? (int) $_GET['id'] : null;
if (!$id) { // === 0 || === null
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
But a more robust solution would involve some type of input string validation / filtering, like PHP's built-in filter_input_array().
(Edited post on Oct/13 since it is still receiving upvotes and it was somewhat confusingly worded.)
User input in $_GET array (as well as the other superglobals) all take the form of strings.
is_int checks the type (i.e. string) of the value, not whether it contains integer-like values. For verification that the input is an integer string, I would suggest either something like ctype_digit or an integer filter (FILTER_VALIDATE_INT—this has the benefit of actually changing the value to type integer). Of course you could also typecast it with (int).
From the PHP documentation for is_int:
Note: To test if a variable is a
number or a numeric string (such as
form input, which is always a string),
you must use is_numeric().
Any user input comes in as a string, because PHP has no way to tell what data type you expect the data to be.
Cast it to an integer or use a regex if you want to make sure it's an integer.
<?php
$id = $_GET["id"];
if ((int) $id == 0) {
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
?>
Try using is_numeric instead of is_int. is_numeric checks to see if it is given something that can be a number ($_GET returns strings I think). is_int checks to see if the variable is of type int
Use is_numeric() to evaluate the content and is_int() to evaluate the type.
Or, you could just use a regex match to check if the string is an integer.
if(preg_match('/^\d+$/',$_GET['id'])) {
// is an integer
}
I want to display an error when a variable have a BLANK value or EMPTY or NULL value. for example variable is shown below:
$mo = strtotime($_POST['MondayOpen']);
and
var_dump($_POST['MondayOpen']) returns string(0) "".
Now I go with below approach
First want to find which type of variable $mo is ?(string or
integer or other)
Which function is better to find that $mo having no value.
I conduct a test with $mo and got these results
is_int($mo);//--Return nothing
is_string($mo); //--Return bool(false)
var_dump($mo); //--Return bool(true)
var_dump(empty($mo));//--Return bool(true)
var_dump($mo==NULL);//--Return bool(true)
var_dump($mo=='');//--Return nothing
Please suggest an optimum and right approach to check the variable integrity
var_dump outputs variables for debugging purposes, it is not used to check the value in a normal code. PHP is loosely typed, most of the time it does not matter if your variable is a string or an int although you can cast it if you need to make sure it is one, or use the is_ functions to check.
To test if something is empty:
if ( empty( $mo ) ) {
// error
}
empty() returns true if a variable is 0, null, false or an empty string.
doing strtotime will return false if it cannot convert to a time stamp.
$mo = strtotime($_POST['MondayOpen']);
if ($mo !== false)
{
//valid date was passed in and $mo is type int
}
else
{
//invalid date let the user know
}
PHP offers a function isset to check if a variable is not NULL and empty to check if a variable is empty.
To return the type, you can use the PHP function gettype
if (!isset($mo) || is_empty($mo)) {
// $mo is either NULL or empty.
// display error message
}
You can check its type using:
gettype($mo);
but null and empty are different things, you can check with these functions:
if (empty($mo))
{
// it is empty
}
if (is_null($mo))
{
// it is null
}
Another way to check if variable has been set is to use the isset construct.
if (isset($mo))
{
// variable has been set
}