Why is this not possible?
if(!empty( _MY_CONST)){
...
But yet this is:
$my_const = _MY_CONST;
if(!empty($my_const)){
...
define( 'QUOTA_MSG' , '' ); // There is currently no message to show
$message = QUOTA_MSG;
if(!empty($message)){
echo $message;
}
I just wanted to make it a little cleaner by just referencing the constant itself.
See the manual: empty() is a language construct, not a function.
empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
So you'll have to use a variable - empty() is really what you want in the first place? It would return true when the constant's value is "0" for example.
Maybe you need to test for the existence of the constant using defined() instead?
Just letting you know that you can do
if(!empty(MY_CONST))
since PHP 5.5.
You can get along with this if for some reason you are still not using PHP 5.5.
if (defined('MY_CONST') && MY_CONST) {
echo 'OK';
}
if (!empty(constant('MY_CONST')) {
...
}
mixed constant ( string $name )
Return the value of the constant indicated by $name, or NULL if the constant is not defined
http://php.net/manual/en/function.constant.php
what about strlen?
if(strlen(MY_CONST) == 0)
If constant defined and need check is empty or not, for example you use it in config file, you can use !MY_CONST:
define('MY_CONST', '');
if (!MY_CONST) {
echo 'MY_CONST is empty';
}
Related
I am trying to write a function to avoid getting variable undefined error. Right now, i have a code like this:
function check($str){
if(isset($str)){
$s = $str;
} else {
$s = "";
}
}
check($_GET['var']);
The get var is not set. I am getting a variable undefined error on my screen. How do i alter my function to not throw this error and just return "" if it is not set? I don't want to have to code 100 if statements to avoid getting variable undefined. Thanks.
We already have in PHP a construct to check that. It is called isset(). With it you can check whether a variable exists. If you would like to create it with some default values if it doesn't exist yet, we also have syntax for it. It's null-coalescing operator.
$_GET['var'] = $_GET['var'] ?? '';
// or since PHP 7.4
$_GET['var'] ??= '';
Although I'm not sure if it is the right way of doing it, for the sake of providing an answer you can pass the variable by reference, this allows you to get away with passing undefined variables and check if it is set inside the function..
function check(&$str){
if(!isset($str)){
$str = "not set";
}
}
check($_GET['var']);
echo $_GET['var'];
I am trying to check defined variables based on passing a single portion of the variable. (The rest of the variable is static and all other portions of it are the same), so I made a test to find out if this is possible.
It does not work, but perhaps I am doing something small that is easily fixed.
define('TEST', 'works');
$test = 't';
echo TES . strtoupper($test);
echo eval('TES . strtoupper('.$test.');');
echo eval('TES . strtoupper(\'$test\');');
echo eval('TES' . strtoupper($test) . ';');
If you want to check if a constant is defined, simply use defined()
<?php
if (defined('TEST')) {
echo TEST;
}
?>
This should work for you:
Just use constant() to build the constant name as string and then pass it to the function.
echo constant("TES". strtoupper($test));
output:
works
'TEST' is not a global variable. It is a constant. The constants have global scope, they can be accessed from any context (given you know the name of the constant you want to use). There is no need to do any hack using eval().
If you generate the name of the constant on runtime for some reason, you can use the PHP function defined() to check if there is a constant already defined having that name and, if the constant exists, you can get its value using the function constant()
Like this:
define('TEST', 'works');
$test = 't';
echo 'TES'.strtoupper($test);
// Compute the constant's name
$name = 'TES'.strtoupper($test);
// Check if the constant exists and get its value
if (defined($name)) {
echo("The constant '".$name."' is already defined.\n");
echo("It's value is: ".constant($name)."\n");
}
I often find myself writing something like this:
$val = (isset($dog->owner->name)) ? $dog->owner->name : "no owner";
Because PHP throws an error if you try to evaluate a variable that does not exist, the following will not work (PHP 5.3 and above for the new shorthand ternary syntax):
$val = ($dog->owner->name) ?: "no owner";
You can achieve the above if you turn off E_USER_NOTICE reporting, which is not something I want to do.
Is there a PHP command that will return the value of a variable if it is defined?
PHP doesn't have anything like this, but you can create your own. The key is passing by reference:
function getVar(&$var, $default=null) {
if( isset($var) ) return $var;
else return $default;
}
$blah = getVar($blah, "my default value");
No there is no command to check if the variable has a value assigned without doing what you've already done. You're going to have to either perform a check or explicitly make sure your variable has a value. Add the owner's name as a parameter in the class constructor or give it a default assignment on object creation. You can also create a method that performs this task so you can reuse the code.
You can try Error control operaors #
#$val = $dog->owner->name ?: "no owner";
echo $val, "\r\n";
And you will get what you want.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
I am getting this error in a PHP class...
Fatal error: Can't use method return
value in write context in
C:\webserver\htdocs\friendproject2\includes\classes\User.class.php
on line 35
Here is the troubled part.
if(isset($this->session->get('user_id')) && $this->session->get('user_id') != ''){
//run code
}
This code is in my contrustor, is a value is not already set for $this->session->get('user_id') then it will return false instead of a Number. So as you can see I was hoping to check if this value is a number or not or not even set.
Any help with fixing appreciated.
You can't use isset for the result of a function. Consider the following code instead:
if( $this->session->get('user_id') ){
//run code
}
isset() only works with variables as
passing anything else will result in a
parse error. For checking if constants
are set use the defined() function.
From the PHP Manual.
You can't use isset on a function. However, since false, 0, and '' all equate to a falsey statement, write your test this way:
if( $id = $this->sessions->get('user_id') ){
// Will only run if $id does not equal '', False, or 0
}
That way you have run your test and assigned the variable in one step.