This is really weird.
Whenever I call something like
if(empty($this->input->post("foo")){//blabla}
The whole PHP is "down" and I get a blank page from the website (even when I don't pass through this empty(input) line).
I know this is not the right method and it is stupid, I change the code to
if(!$this->input->post("foo")){//blabla}
Better I guess ?
Seriously, how come the empty(input) breaks down the entire PHP page ? (I can't get any echo "something").
From the manual:
Note:
empty() only checks variables as anything else will result in a parse
error. In other words, the following will not work:
empty(trim($name)).
Update:
From php 5.5, empty() supports expressions too.
Changelog:
5.5.0 empty() now supports expressions, rather than only variables.
You cannot use empty with functions, and neither do you need to. empty is a special construct that only works on variables and triggers a fatal error otherwise. See The Definitive Guide To isset And empty.
You dont need to use empty with input class because if the post variable does not exists or contains null value input class returns false which automatically fails the if condition and your else block would work...
Related
I was wondering if we could check for all undefined and null variables in JSP using its built-in functions?
I know I can build a function to do that, but I need a lazy solution.
<c:if test="${name == null}">variable name is undefined</c:if>
For testing you can define and undefine a variable using:
<c:set var="name" value="Petra"/>
<c:set var="name" value="${null}"/>
To state you are using the core JSTL tags add this to the top of the page:
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
There are No built-in functions to check this in a JSP, so I guess you would have to make one, which I think should be a fairly simple task if you take the bookish meaning of null.
If not bookish then null is sort of an overloaded term, it could mean any of the following in general usage:
actually null String, which could throw NullPointerException.
"", empty string which might be called null.
"null"
An acutally null array. :-)
An empty array.
An array with just null objects ...
So you can build a method to include these or other cases you can think of for null-check or just the basic-primitive-unembellished null-check.
In Java I suppose there is no such thing as an undefined variables, since it is a statically typed language and compiler would catch any of these so called undefined errors :-)
In PHP (since I think you took this function from there) you have these things because it is a scripting language and is not a statically typed language like Java.
Hope this helps.
Instead of checking against null, you can use this snippet:
<c:if test="${not name}">variable name is undefined</c:if>
for checking variable is sent or not use following function
request.getParameterMap().containsKey("variable")
if(request.getParameterMap().containsKey("name"))
{
out.print(request.getParameter("name"));
}
I was recently placed on a project with some PHP, and I don't know much about PHP. There are a couple instances in the site where upon clicking a button, the user is redirected to another page with some URL parameters. The next page then uses $_GET to get those parameters and move on.
Another issue in the code caused the page to reload the second page without the parameters, so using $_GET would return errors, but with the other issue fixed, I can't think of a reason why the parameters wouldn't be there.
While debugging, I came across advice to always check $_GET using isset(), but theoretically there should never be an instance when those parameters aren't there (otherwise something else is really wrong with the server or the code).
Is it still worth putting in the checks and working out a backup solution, even though there shouldn't be a need for it? I want to make sure I'm not ignoring some other potential issue that I may not be aware of.
It is always good practice+recommended to check your variables before applying any logic.
!empty() is recommended to use instead of isset() because it check both that variable is initialized and have some values too.
In case of array count($array)>0 can be used as a check.
Why to use !empty() check here:- !empty() Vs isset()
If you are expecting or requiring data to be sent via $_GET you should check if it's set. Especially since that data can be easily manipulated. Also like #Alive to Die said !empty() is better.
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.
I just came across a strange situation. When I try the following code in $ php -a, I receive an error:
php > var_dump(isset(null));
PHP Fatal error: Cannot use isset() on the result of an expression
(you can use "null !== expression" instead) in php shell code on line
1
But when I do the same thing with empty(), everything is ok:
php > var_dump(empty(null));
bool(true)
Can anyone explain why I receive an error when I try isset(null)?
Update
Thank you all for your answers. I asked this question just to make sense of why isset() is behaving differently from empty().
To me, both of them are php functions and both accept a parameter. So, as any other function in php, calling isset(null) should be a valid statement. Aren't we passing null as a value to isset() function? So why php consider it as an expression?
Testing if an expression is "set" doesn't make sense. As per the manual, isset is used to
Determine if a variable is set and is not NULL.
If you want to check if an expression is null, use is_null, or as the error message suggests, null !== expression.
The manual for empty suggests something similar:
Determine whether a variable is considered to be empty.
until you read slightly further down, in the changelog:
5.5.0 empty() now supports expressions, rather than only variables.
Prior to this, empty(null) would have thrown an error along the lines of
Parse error: syntax error, unexpected ')', expecting :: (T_PAAMAYIM_NEKUDOTAYIM) in ... on line ...
Ok, I found something that I didn't know before in php which could be the answer to this question. According to the manual, isset() is not a function, but rather a language construct like if ... else, foreach and while:
Note: Because this [referring to isset()] is a language construct and not a function, it cannot be called using variable
functions.
There are a few more of these language constructs that can be easily confused with functions, including:
unset()
empty()
die()
include()
So now it makes sense why isset(null) doesn't work. We are trying to use a construct that expects a variable inside the parenthesis. Providing anything else other than a variable will result in syntax error during parsing of the code.
i recently had to do a "test" for a job, and i got feed back saying that this statement was incorrect:
$images = $flickr->get_images(5, !empty($_GET['pg']) ? $_GET['pg'] : 1);
The "supposed" error was generated via the ternary operator on the first time the page was loaded, as there was no "?pg=1" (or whatever) passed via the query string.
The feed back said i should have used isset instead. I have looked at various posts both here (question 1960509) and blogs, but cannot find any definitive answer.
Is this really an error? How can i replicate this issue? do i need to put on E_STRICT or something in my php.ini file? Or might this be due to an older version of php?
Note: please don't tell me about how i should validate things.. i know this... it was a test to just see if i could use the flickr api calls.
This is perfectly fine. empty is not an actual function, it's a language construct. It does not issue a warning if a variable is not set (in that case the variable is considered empty, thus the 'function' returns TRUE just as you want), and additionally it checks for empty or zero values.
You could see empty as a normal isset check with an additional loose comparison to FALSE:
empty($var) === (!isset($var) || $var == FALSE)
$images = $flickr->get_images(5, (isset($_GET['pg']&&($_GET['pg']))) ? $_GET['pg'] : 1);
without isset you'll get error so combine them
I'd use
$images = $flickr->get_images(5, array_key_exists('pg', $_GET) ? $_GET['pg'] : 1);
Combine with !empty($_GET['pg']) if needed (i.e. array_key_exists('pg', $_GET) && !empty($_GET['pg'])), but array_key_exists is the intended function for this job.
I think in a situation like this isset is the correct function to use as it is checking the existence of the array element rather than checking if the value of the element has been set. As Martin notes, the best thing to do here is combine them as this will only check the value if the element exists, meaning that the error will not occur on the first page load.
Also, I think this will only give a warning if E_NOTICE is on (or perhaps E_WARNING as well)
The reason you would get an error is because the empty function is designed to check the value of an existing variable, whearas isset() is designed to tell you whether a variable has been instantiated, however because empty() is a language construct technically it doesn't throw an error or create a warning so most people don't see the difference.
From the docs:
empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.
isset — Determine if a variable is set and is not NULL. So "isset" is the correct function to use for checking for value is set or not.
More details :http://php.net/manual/en/function.isset.php
Ran into a strange problem in PHP today and I'm wondering if someone can explain it. While comparing two arrays I initially tried something like this:
echo empty(array_diff( array('foo','bar') , array('bar','foo') ))
This results in the following error:
Fatal Error: Can't use function return value in write context
Rewriting this as...
$dif = array_diff( array('foo','bar') , array('bar','foo') );
echo empty($dif);
...works perfectly. Empty should just be evaluating the value passed in to it, not writing to it, so what's going wrong here? Tested in both PHP 5.2.10 and PHP 5.3.2.
I've resolved the issue by using !count() instead of empty(), but I'm curious why it doesn't work in the first place. Is empty() trying to alter the result from array_diff?
Check the manual on empty():
Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)).
empty(), like e.g. echo() and die(), is a language construct, and therefore has different rules than a normal function (in which your example would work fine).