PHP POST array with empty and isset [duplicate] - php

This question already has answers here:
What's the difference between 'isset()' and '!empty()' in PHP?
(7 answers)
Closed 1 year ago.
I have the following multiple checkbox selection:
<input type="checkbox" name="fruit_list[]" value="apple">Apple
<input type="checkbox" name="fruit_list[]" value="banana">Banana
<input type="checkbox" name="fruit_list[]" value="mango">Mango
<input type="checkbox" name="fruit_list[]" value="orange">Orange
form connects to processor.php via POST method. Validation:
if ( empty($_POST['fruit_list']) ){
echo "You must select at least one fruit.<br>";
} else{
foreach ( $_POST['fruit_list'] as $frname ){
echo "Favourite fruit: $frname<br>";
}
}
My Questions (above code works! But unclear points for me):
If I don't select any of checkboxes and then submit form, does $_POST array contain an index called $_POST['fruit_list'] ?
Assuming your answer "No", then how is it possible to use empty() to that non existed array element? Non-existed array element means NULL ?
What is the difference using !isset($_POST['fruit_list']) instead of empty()
I understand the difference between empty() and isset() generally.
Can you explain in this context of example?

If I don't select any of checkboxes and then submit form, does $_POST array contain an index called $_POST['fruit_list']
No, key fruit_list does not exist
To check if key exists in array better use array_key_exists because if you have NULL values isset returns false
But in your case isset is a good way
isset - Determine if a variable is set and is not NULL (have any value).
empty - Determine whether a variable is empty (0, null, '', false, array()) but you can't understand if variable or key exists or not
For example:
$_POST['test'] = 0;
print 'isset check: ';
var_dump(isset($_POST['test']));
print 'empty check: ';
var_dump(empty($_POST['test']));
$_POST['test'] = null;
print 'isset NULL check: ';
var_dump(isset($_POST['test']));
print 'key exists NULL check: ';
var_dump(array_key_exists('test', $_POST));
isset check: bool(true)
empty check: bool(true)
isset NULL check: bool(false)
key exists NULL check: bool(true)

use print_r() to print the post data..
<?php
echo "<pre>"; print_r($_POST);
if (empty($_POST['fruit_list']) ){
echo "You must select at least one fruit.<br>";
}
else{
foreach ( $_POST['fruit_list'] as $frname ){
echo "Favourite fruit: $frname<br>";
}
}
?>
If you do not select any checkbox then you will not get $_POST['fruit_list'], array index fruit_list does not exist in array
for difference between isset() and empty() Visit Here

Answer:
1. $_POST array does not contain $_POST['fruit_list']
2. First answer is "No".A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.see in php.net
3. Empty checks if the variable is set and if it is it checks it for null, "", 0, etc.
Isset just checks if is it set, it could be anything not null. see

Related

empty text input means empty $_POST[] element? (Null coallesce)

So my question is:
If I don't write anything in an input
<input type="text" name="test">
in a simple form with post method, when I receive the $_POST array in my action url, the $_POST["test"] exists as empty string ($_POST["test"] => "").
So I can't use null coalesce because $var = $_POST["test"] ?? 'default'; because it is always $var = ""; (as is normal).
Any way to solve this problem?
for Only check if a PARTICULAR Key is available in post data
if (isset($_POST['test']) )
{
$textData = '+text'.$_POST['test'];
echo $textData;
}

How to check the query string of my current url for a specific key-value pair?

How I can identify in PHP if my current URL contains this text special_offer=12.
For example, if my domain URL is http://www.example.com/newproducts.html?special_offer=12 then echo something.
Alternatively, the domain can be http://example.com/all-products.html?at=93&special_offer=12
This text will always be the same: special_offer=12.
You can access the Query parameters using the $_GET superglobal, In this case:
if(isset($_GET['special_offer']) && $_GET['special_offer'] == 12){
echo "Something";
}
if (isset($_GET['special_offer'] {
do something...
}
Write var_dump($_GET);
to see how superglobal $_GET works
Just by checking the $_GET var ?
if(!empty($_GET["special_offer"]) && $_GET["special_offer"] ==12 ){
//You're code here
}
You Can Access To Query Parameter Using Get Like This:
if(isset($_GET['special_offer'] == 12)){
//echo " ECHO YOUR CODE HERE ";
}
OR
NOTE: Avoid To Use isset() and USE !empty() ..Because isset() accept the null value also to store , So avoid to use it !!
if(!empty($_GET['special_offer']) && $_GET['special_offer'] == 12){
//echo " ECHO YOUR CODE HERE ";
}
NOTE:
Empty checks if the variable is set and if it is it checks it for null, "", 0, etc
1 Isset just checks if is it set, it could be anything not null
2 With empty, the following things are considered 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)
Reference: http://php.net/manual/en/function.empty.php

if array undefined

How do I check if an array is undefined?
I am using isset and empty but both of them are not working for an undefined array.
This is my code:
if (isset($content['menu']['main'])){
echo 'there is menu';
}
use this code as specified by Rikesh and mimipc
$arr = array("menu"=>array("main"=>1));
if (is_array($arr) && array_key_exists('menu', $arr)) {
echo "array";
}
working example http://codepad.viper-7.com/Q3gTwn
Based on your code, I think you're looking for the function array_key_exists().
$content = array('menu'=>array());
echo isset($content);
>>> 1
echo array_key_exists('menu', $content);
>>> 1
if ( array_key_exists('main', $content['menu']) ) {
echo "Main menu exists";
} else {
echo "Main menu does not exist";
}
>>> Main menu does not exist
isset() will not work, because the variable $content is set, and the array may not be empty, so empty() will also not work. You want to see if the main key exists in the $content['menu'] array.
You can check if an array element exists with in_array:
in_array('one', array('two', 'three', 'four')); // false
And you can check array-indexes with array_key_exists:
array_key_exists('metallica', array('metallica' => 'worst than megadeth')); // true
With the isset function you only check if the array or variable is not equal to NULL and if it contains a value which can be interpreted as boolean True or False, integers larger than 0 and if the variable value (or array key/index/element) is not equal to NULL.
I usualy check if variable is set with: is_null, and it can be used to check if an array index or an element is defined within that same array.
EDIT:
You can also check if a variable is array with: (sizeof($something) > 0) or with: is_array function(s).

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
}

What does ? ... : ... do? [duplicate]

This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 5 years ago.
$items = (isset($_POST['items'])) ? $_POST['items'] : array();
I don't understand the last snippet of this code "? $_POST['items'] : array();"
What does that combination of code do exactly?
I use it to take in a bunch of values from html text boxes and store it into a session array. But the problem is, if I attempt to resubmit the data in text boxes the new array session overwrites the old session array completely blank spaces and all.
I only want to overwrite places in the array that already have values. If the user decides to fill out only a few text boxes I don't want the previous session array data to be overwritten by blank spaces (from the blank text boxes).
I'm thinking the above code is the problem, but I'm not sure how it works. Enlighten me please.
This is a ternary operator:
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
That last part is known as the conditional operator. Basically it is a condensed if/else statement.
It works like this:
$items =
// if this expression is true
(isset($_POST['items']))
// then "$_POST['items']" is assigned to $items
? $_POST['items']
// else "array()" is assigned
: array();
Also here is some pseudo-code that may be simpler:
$items = (condition) ? value_if_condition_true : value_if_condition_false;
Edit: Here is a quick, pedantic side-note: The PHP documentation calls this operator a ternary operator. While the conditional operator is technically a ternary operator (that is, an operator with 3 operands) it is a misnomer (and rather presumptive) to call it the ternary operator.
It is the same as:
if (isset($_POST['items']){
$items = $_POST['items'];
} else {
$items = array();
}
Look at Paolo's answer to understand the ternary operator.
To do what you are looking at doing you might want to use a session variable.
At the top of your page put this (because you can't output anything to the page before you start a session. I.E. NO ECHO STATEMENTS)
session_start();
Then when a user submits your form, save the result in this server variable. If this is the first time the user submitted the form, just save it directly, otherwise cycle through and add any value that is not empty. See if this is what you are looking for:
HTML CODE (testform.html):
<html>
<body>
<form name="someForm" action="process.php" method="POST">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input type="submit">
</form>
</body>
</html>
Processing code (process.php):
<?php
session_start();
if(!$_SESSION['items']) {
// If this is the first time the user submitted the form,
// set what they put in to the master list which is $_SESSION['items'].
$_SESSION['items'] = $_POST['items'];
}
else {
// If the user has submitted items before...
// Then we want to replace any fields they changed with the changed value
// and leave the blank ones with what they previously gave us.
foreach ($_POST['items'] as $key => $value) {
if ($value != '') { // So long as the field is not blank
$_SESSION['items'][$key] = $value;
}
}
}
// Displaying the array.
foreach ($_SESSION['items'] as $k => $v) {
echo $v,'<br>';
}
?>
yup... it is ternary operator
a simple and clear explanation provided here, in which the author said it is like answering : “Well, is it true?”
the colon separates two possible values (or). the first value will be chosen if the test expression is true. the second (behind the colon) will be chosen if the first answers is false.
ternary operator very helpfull in creating variable in php 7.x, free of notice warning. For example"
$mod = isset($_REQUEST['mod']) ? $_REQUEST['mod'] : "";
Basically if $_POST['items'] exists then $items gets set to it otherwise it gets set to an empty array.
It is a ternary operator that essentially says if the items key is in the $_POST then set $items to equal the value of $_POST['items'] else set it to a null array.
I figured it's also worth noting that ?: is a separate operator, where:
$one = $two ?: $three;
$one = two() ?: three();
is shorthand for:
$one = $two ? $two : $three;
$one = two() ? two() : three();
Aside from typing less, the runtime advantage is that, if using a function like two(), the function would only be evaluated once using the shorthand form, but possibly twice using the long form.

Categories