how to print the result of is_int () - php

I already know what is_int() is used for. But I only know that to print the result of this function we need to use the var_dump() function. So can someone explain to me why echo, print or print_r() cannot display is_int()?
$var1 = '123';
var_dump(is_int($var1)); // return False;
$var2 = '123';
echo/print/print_r($var2); // Not working

In PHP (boolean) false will be converted to "" (empty string) and boolean (true) will be converted to 1 so when you print_r and the return value is false then you will get the empty string. So either use the var_dump to get the variable details where it will give you the type and value both.
Here is the way to echo the true and false based on the result. you can use this too
$var1 = '123';
echo is_int($var1)?'true':'false';

Related

isset() returns true from a string variable accessed as an array with any key

I face a problem like this:
$area="Dhaka";
isset($area); //returns true which is OK
isset($area['division']); //returns true why?
// actually, any array key of area returns true
isset($area['ANY_KEY']);//this is my question 1
isset($area['division']['zilla');//now it returns false.
//as I know it should returns false but why previous one was true.
Now if I do this:
$area['division'] = "Dhaka";
isset($area); // returns true which is OK
isset($area['division']); // returns true it's also OK
isset($area['ANY_KEY']); // returns false. I also expect this
isset($area['division']['ANY_KEY']); // returns true why? question #2
Basically both of my questions are the same.
Can anyone explain this?
As with every programming language in existence, a string is stored as an array of characters.
If I did:
$area = "Dhaka";
echo $area[0];
It would return D.
I could also echo the whole string by doing:
echo $area[0].$area[1].$area[2].$area[3].$area[4];
PHP will also type juggle a string into 0 when passed in a manner that accepts only integers.
So by doing:
echo $area['division'];
You would essentially be doing:
echo $area[0];
and again, getting D.
That's why isset($area['division']) returns a true value.
Why doesn't $area['foo']['bar'] (aka $area[0][0]) work? Because $area is only a single-dimension array.
The best approach to handle this problem when you're working with a variable that could either be a string or an array is to test with is_array() before trying to treat your variable as an array:
is_array($area) && isset($area['division'])
PHP lets you treat a string as an array:
$foo = 'bar';
echo $foo[1]; // outputs 'a'
So
$area['division']
will be parsed/executed as
$area[0];
(the keys cannot be strings, since it's not REALLY an array, so PHP type-converts your division string by its convert-to-int rules, and gives 0), and evaluate to the letter D in Dhaka, which is obviously set.
Okay, here's a solution rather than explaining why isset isn't going to work properly.
You want to check if an array element is set based on it's index string. Here's how I might do it:
function isset_by_strkey($KeyStr,$Ar)
{
if(array_key_exists($KeyStr,$Ar))
{
if(strlen($Ar[$KeyStr]) > 0 || is_numeric($Ar[$KeyStr] !== FALSE)
{
return TRUE;
}
return FALSE;
}
}
isset_by_strkey('ANY_KEY',$area); // will return false if ANY_KEY is not set in $area array and true if it is.
The best way to access a linear array in php is
// string treated as an linear array
$string= "roni" ;
echo $string{0} . $string{1} . $string{2} . $string{3};
// output = roni
It is expected behaviour.
PHP Documentation covers this
You can try empty() instead.
If it is returning true for keys that do not exist there's nothing you can do; however, you can make sure that it doesn't have a negative effect on your code. Just use array_key_exists() and then perform isset() on the array element.
Edit: In fact, using array_key_exists() you shouldn't even need isset if it is misbehaving just use something like strlen() or check the value type if array_key_exists returns true.
The point is, rather than just saying isset($Ar['something']) do:
if(array_key_exists('something',$Ar) )
and if necessary check the value length or type. If you need to check the array exists before that of course use isset() or is_array() on just the array itself.

Do all php types return a bool?

I'm currently building a website and I come across the case where I can do:
if (myString)
if (myArray),
and it seems to "return" true whenever there is data inside the variable. At least, that's what I think.
E.g.
$testVar = "test";
if ($testVar)
echo $testVar;
else
echo "Empty";
When i assert $testVar = "", then it echos "Empty".
I'm wondering if this is a defined feature of PHP, that any type will return true if it is not null or empty, as in other languages you need to do if($testVar = "") or so on.
Additionally, if this does indeed return true on all types if the variable is not empty, and I also want to check if the variable exists, would:
if (isset($testVar) && $testVar) be okay to use (in terms of practices)
I have searched for questions but can't find an answer to this exact question. To summarize:
Can any type return a bool, provided that it is not empty?
Thanks.
These types do not return true, but they are, instead, cast to true. PHP is a weak typed language, so it will automatically try to convert a variable to the correct type when required. In most instances, this means that a non-empty variable will return true.
This resource here will give you more information. Take a look at the "Converting to boolean" section, specifically.
http://www.php.net/manual/en/language.types.boolean.php
You can not check if a string is empty that way. Consider this:
$test = "0";
if ($test)
echo $test;
else
echo "Empty";
The code above prints "Empty", because "0" is a falsy value. See Booleans, section "Converting to boolean".
So the answer is:
All types can be converted to booleans, but the result might not be what you want.
The variables don't "return" a bool, but any variable can evaluate to either true or false.
Best practice is to be strict on your comparisons and not just do if($var)
For detailed comparison information, see: http://us3.php.net/manual/en/types.comparisons.php
conditional always return bool
if you need to check any empty values you need to use equalsto operator for check values
if($testVar == "") // check is $testVar is empty or not return bool-true/false
best to use functions like empty()
if(empty($testVar))
In this example when you are testing string variables:
$testVar = "test";
if ($testVar)
echo $testVar;
else
echo "Empty";
What you are asserting is if variable $testVar is set (not if it's empty or not). The variable themselves don't have a return type, but it's in the context they are used in a control flow operator such as an if statement.
i.e. if ($testVar) is same as if (isset($testVar)) (when $testVar is a string)
However, there are other cases like this:
$testVar = "0";
if ($testVar)
echo $testVar;
else
echo "Empty";
In this case, you will get "Empty" because $testVar is evaluated as a int 0.
However; if you had this:
$testVar = " 0"; // notice the space in front of 0
if ($testVar)
echo $testVar;
else
echo "Empty";
This will echo back the $testVar because the variable is both set and has a string value.
When you want to check for empty string, you have several options:
if (empty($testVar))
if (strlen($testVar)) or if (strlen($testVar) > 0) (both same)
etc...

PHP: is_int return wrong result

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"];

returning true outputs 1 but returning false outputs nothing

It's not very important but I was just curious to know the difference.
echo isA("A"); //outputs 1
echo isA("B"); //outputs nothing. why doesn't it output 0?
Anybody can shed somelight on this matter? It does seem to me as a double standard when you look at it from the point of view that "true" outputs as "1" but "false"does not output "0".
Again, no big deal but I think there must be a reason for PHP to be designed like that. Knowing that may give some more insight into this beautiful language.
A true value will manifest itself as a visible 1, but a false value won't. So, tell me what's the advantage of this method?
example function I referred above;
function isA($input){
if ( $input == "A" ):
return true;
else:
return false;
endif;
}
A boolean TRUE value is converted to the string "1". Boolean FALSE is
converted to "" (the empty string). This allows conversion back and
forth between boolean and string values.
http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting
If you want to print a boolean for debugging you can use var_dump or print_r.
Because when false is casted to string it becomes '' -- empty string.
To see the difference use var_dump(); instead of echo
var_dump((string) true);
var_dump((string) false);

In where shall I use isset() and !empty()

I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.
So you can use empty() to check that a user typed something.
Is it true that the isset() function treats an empty string as TRUE?
Then in which situations should I use isset()? Should I always use !empty() to check if there is something?
For example instead of
if(isset($_GET['gender']))...
Using this
if(!empty($_GET['gender']))...
isset vs. !empty
FTA:
"isset() checks if a variable has a
value including (False, 0 or empty
string), but not NULL. Returns TRUE
if var exists; FALSE otherwise.
On the other hand the empty() function
checks if the variable has an empty
value empty string, 0, NULL or
False. Returns FALSE if var has a
non-empty and non-zero value."
In the most general way :
isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
empty tests if a variable (...) contains some non-empty data.
To answer question 1 :
$str = '';
var_dump(isset($str));
gives
boolean true
Because the variable $str exists.
And question 2 :
You should use isset to determine whether a variable exists ; for instance, if you are getting some data as an array, you might need to check if a key isset in that array.
Think about $_GET / $_POST, for instance.
Now, to work on its value, when you know there is such a value : that is the job of empty.
Neither is a good way to check for valid input.
isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
! empty() is not sufficient either because it rejects '0', which could be a valid value.
Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:
if( isset($_GET['gender']) and ($_GET['gender'] != '') )
{
...
}
But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female","FileNotFound")).
For that, see Josh Davis's answer.
isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.
So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:
$var = "";
var_dump(isset($var));
The type comparison tables in PHP’s manual is quite handy for such questions.
isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)
If you have a $_POST['param'] and assume it's string type then
isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'
is identical to
!empty($_POST['param'])
isset() is not an effective way to validate text inputs and text boxes from a HTML form
You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.
Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.
When and how to use:
isset()
True for 0, 1, empty string, a string containing a value, true, false
False for null
e.g
$status = 0
if (isset($status)) // True
$status = null
if (isset($status)) // False
Empty
False for 1, a string containing a value, true
True for null, empty string, 0, false
e.g
$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
isset() vs empty() vs is_null()
isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...
Pascal MARTIN... +1
...
empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...
isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.
isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.
isset($variable) === (#$variable !== null)
empty($variable) === (#$variable == false)
I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:
It's enough to check if the input is '' or null, because:
Request URL .../test.php?var= results in $_GET['var'] = ''
Request URL .../test.php results in $_GET['var'] = null
isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').
empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.
If you want to treat '0' as empty, then use empty(). Otherwise use the following check:
$var .'' !== '' evaluates to false only for the following inputs:
''
null
false
I use the following check to also filter out strings with only spaces and line breaks:
function hasContent($var){
return trim($var .'') !== '';
}
Using empty is enough:
if(!empty($variable)){
// Do stuff
}
Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.
I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the # prefix you can safely check if is not empty and avoid the notice if the var is not set:
if( isset($_GET['var']) && #$_GET['var']!='' ){
//Is not empty, do something
}
$var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
echo '$var is set even though it is empty';
}
Source: Php.net
isset() tests if a variable is set and not null:
http://us.php.net/manual/en/function.isset.php
empty() can return true when the variable is set to certain values:
http://us.php.net/manual/en/function.empty.php
<?php
$the_var = 0;
if (isset($the_var)) {
echo "set";
} else {
echo "not set";
}
echo "\n";
if (empty($the_var)) {
echo "empty";
} else {
echo "not empty";
}
?>
!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations
<?php
$array = [ "name_new" => "print me"];
if (!empty($array['name'])){
echo $array['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array2 = [ "name" => NULL];
if (!empty($array2['name'])){
echo $array2['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array3 = [ "name" => ""];
if (!empty($array3['name'])){
echo $array3['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array4 = [1,2];
if (!empty($array4['name'])){
echo $array4['name'];
}
//output : {nothing}
////////////////////////////////////////////////////////////////////
$array5 = [];
if (!empty($array5['name'])){
echo $array5['name'];
}
//output : {nothing}
?>
Please consider behavior may change on different PHP versions
From documentation
isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise
https://www.php.net/manual/en/function.isset.php
empty() does not exist or if its value equals FALSE
https://www.php.net/manual/en/function.empty.php
(empty($x) == (!isset($x) || !$x)) // returns true;
(!empty($x) == (isset($x) && $x)) // returns true;
When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.
if(empty($yourVal)) {
echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
echo "<P>YES isset - $yourVal"; // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}

Categories