I have the following $_POST function to check if the fields of 'start', 'middle' and 'end' is empty or not.
if(!empty($_POST['start'])) {
$description = "a sentence".$_POST['start']." with something in the START.";
}
if(!empty($_POST['middle'])) {
$description = "a sentence".$_POST['middle']." with something in the MIDDLE.";
}
if(!empty($_POST['end'])) {
$description .= "a sentence".$_POST['end']." with something in the END.";
}
I want to check the values in one function, in other words I want to check multiple values at the same time. I have seen few method but not sure which one is right, using comma or && or ||, something like below ...
if(!empty($_POST['start']) , (!empty($_POST['middle']) , (!empty($_POST['end']))
or
if(!empty($_POST['start']) && (!empty($_POST['middle']) && (!empty($_POST['end']))
or
if(!empty($_POST['start']) || (!empty($_POST['middle']) || (!empty($_POST['end']))
Can anyone tell me the right code for this kind of formation?
here are some basic.. i made it as a comment(as i was not sure if this is the thing you asked for) but i guess an answer would be appropriate with a bit of details.
the AND operatior
the && will check every condition and if all are true it will return true...
take it like this
if(FALSE && TRUE)
it will always return False and if will not execute because one of the condition is false
The OR operator
THe || will check the first condition if its true it will return true else check the second condition If all are false(not even a single is true) it will return false.
again following the previous example
if(TRUE || False || False)
now the compiler checks the first condition if its true it will ignore the next two conditions and return true.
if(FALSE || FALSE || FALSE) - this will return false as all are false
THe comma Operator
if you , operatior then the last condition to the right will be evaluated and if it is true then it will return true else false
example
if(True,True,True,False) - it will return false
if(FALSE, TRUE, FALSE, TRUE) - it will return true
so choose the operator according to your logic.
USE THIS :
if((!empty($_POST['start'])) && (!empty($_POST['start'])) && (!empty($_POST['start'])));
Your looking for something like:
// Establish valid post key values
$valid_post_variables = array_flip( ['start', 'middle', 'end'] );
// Fetch post data
$post = $_POST;
// $result will contain the values of post where the keys matched valid
$result = array_intersect_key( $post, $valid_post_variables );
// if the resulting array contains our 3 options, its go time
if ( count( $result ) == 3 ) {
//start middle and end where all passed via POST
}
function insertPost($before, $offset, $after)
{
if(!empty($_POST[$offset])) {
return $before . $_POST[$offset] . $after;
}
return '';
}
$description = insertPost('a sentence', 'start', ' with something in the START.');
Related
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL; and $_POST['x'] = '';
isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
isset($_POST['fromPerson'])
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null
The other option is isset() which which will check if array key exists and if it was set
The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset() and empty() can be good as well.
In that case using method isset is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.
Try isset($_POST['fromPerson'])?
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
if( isset($_POST['fromPerson']) ) is right.
You can use a function and return, better then directing echo.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
I recently came up with this:
class ParameterFetcher
{
public function fetchDate(string $pDate):string{
$myVar = "";
try{
if(strlen($_POST[$pDate]) > 0){
$myVar = $_POST[$pDate];
}
}catch (Exception $faild){
die("field NULL or not set for $pDate");
}
[ ... other stuff ]
to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.
I want to perform an action when the url is /bookings , but not /bookings/something-else
I tried this...
if ($_SERVER['REQUEST_URI'] == '/bookings') {
// do stuff....
}
But it fails when the user is on the /bookings page and searches, at which point queries are added to the url, e.g. /bookings?search=this
I have also tried this...
if (strpos($_SERVER['REQUEST_URI'],'/bookings') !== false && strpos($_SERVER['REQUEST_URI'],'/bookings/') == false ) {
// do stuff...
}
But this still executes on /bookings/some-thing and i cant figure out why?
You'll be better off using a dedicated method for URL parsing, rather than using string manipulation. PHP's parse_url function is perfect for this:
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($path === '/bookings') {
...
}
Try this condition. first will make exact string. while seocnd match with query sring
if ($_SERVER['REQUEST_URI'] == '/bookings' || strpos($_SERVER['REQUEST_URI'],'/bookings?') !== false) {
// do stuff....
}
OR use === while matching false/ otherwise 0 and false become equal
if (strpos($_SERVER['REQUEST_URI'],'/bookings') !== false && strpos($_SERVER['REQUEST_URI'],'/bookings/') === false ) {
I have following part of code:
if (($product->uploadable_files != $files_count || $product->text_fields != $text_count) && !count($this->errors) && !$product->update())
$this->errors[] = Tools::displayError('An error occurred while updating the custom configuration.');
How come (I'm completly lost atm) it does not call Tools::displayError nor $product->update()
At last one of those, should be called. And it is not.
This probably means it doesn't even reach that point. You can group the if-statement in three groups:
1st: $product->uploadable_files != $files_count || $product->text_fields != $text_count
2nd: !count($this->errors)
3rd: !$product->update()
If one of those groups is false, the entire condition will be false. And if 1st is false, it doesn't even reach 2nd and 3rd. And if 2nd is false, it doesn't reach 3rd.
Also, count never returns false. You're probably checking whether $this->errors is empty, so just use empty($this->errors).
To expand on treegarden's answer,
count() can evaluate to true if its handled incorrectly.
var_dump(count([])); # 0
var_dump(count([]) == false); # true
var_dump(count([]) === false); # false
Count returns the number of elements in in the first parameter. If the parameter is not an array or object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
Instead use empty():
var_dump(!empty([])); # false
&& checks if both are true. If first one is false, it ends there, doesnt go anywhere else, it is a short-circuit as manual says. Same goes for ||.
http://php.net/manual/en/language.operators.logical.php
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
// --------------------
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
var_dump($e, $f);
// --------------------
// "&&" has a greater precedence than "and"
// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;
// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;
var_dump($g, $h);
?>
I'm sorry for the vaguely described title. This is what I want:
if($a[$f] === false || $a[$g] === false || $a[$h] === false || $a[$i] === false || $a[$j] === false)
{
// do something
}
I want to do something with the condition that actually triggered the statement (if a[$f] = true and a[$g] = false, I want to do something with $g).
I know that in this case, the first statement that went true (i.e. $a[$g] == false) triggers. But is there any way to do something with $g? I've never seen this in my programming life before and can't seem to find anything about it.
Thanks in advance.
--- Edit ---
I forgot to mention: I'm using a function on all the array data. So, shortened, I get this:
if(valid($a[$f]) === false || valid($a[$g]) === false)
{
// do something
}
--- Edit 2 ---
This piece of OOP-based PHP, where I'm in a class, is my code.
if($this->validatedText($product[$iName]) == false ||
$this->validatedUrl($product[$iUrl]) == false ||
$this->validatedNumber($product[$iTax]) == false ||
$this->validatedValuta($product[$iPrice]) == false ||
$this->validatedText($product[$iArticleNumber]) == false ||
$this->validatedText($product[$iDescription]) == false ||
$this->validatedText($product[$iMetaDescription]) == false ||
$this->validatedText($product[$iTitle]) == false)
{
// do something with the first iVariable
}
Simplest solution will be
if(false!==($sIndex = array_search(false, $a, 1)))
{
//your $sIndex is first index with false value
}
if you want all keys, you may use array_filter(), like this:
$rgFalse = array_keys(array_filter($a, function($x)
{
//here valid is your function
return false===valid($x);
}));
I'm trying to check whether a $_POST exists and if it does, print it inside another string, if not, don't print at all.
something like this:
$fromPerson = '+from%3A'.$_POST['fromPerson'];
function fromPerson() {
if !($_POST['fromPerson']) {
print ''
} else {
print $fromPerson
};
}
$newString = fromPerson();
Any help would be great!
if( isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Simple. You've two choices:
1. Check if there's ANY post data at all
//Note: This resolves as true even if all $_POST values are empty strings
if (!empty($_POST))
{
// handle post data
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
(OR)
2. Only check if a PARTICULAR Key is available in post data
if (isset($_POST['fromPerson']) )
{
$fromPerson = '+from%3A'.$_POST['fromPerson'];
echo $fromPerson;
}
Surprised it has not been mentioned
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['fromPerson'])){
Everyone is saying to use isset() - which will probably work for you.
However, it's important that you understand the difference between
$_POST['x'] = NULL; and $_POST['x'] = '';
isset($_POST['x']) will return false on the first example, but will return true on the second one even though if you tried to print either one, both would return a blank value.
If your $_POST is coming from a user-inputted field/form and is left blank, I BELIEVE (I am not 100% certain on this though) that the value will be "" but NOT NULL.
Even if that assumption is incorrect (someone please correct me if I'm wrong!) the above is still good to know for future use.
isset($_POST['fromPerson'])
The proper way of checking if array key exists is function array_key_exists()
The difference is that when you have $_POST['variable'] = null it means that key exists and was send but value was null
The other option is isset() which which will check if array key exists and if it was set
The last option is to use empty() which will check if array key exists if is set and if value is not considered empty.
Examples:
$arr = [
'a' => null,
'b' => '',
'c' => 1
];
array_key_exists('a', $arr); // true
isset($arr['a']); // false
empty($arr['a']); // true
array_key_exists('b', $arr); // true
isset($arr['b']); // true
empty($arr['b']); // true
array_key_exists('c', $arr); // true
isset($arr['c']); // true
empty($arr['c']); // false
Regarding your question
The proper way to check if value was send is to use array_key_exists() with check of request method
if ($_SERVER['REQUEST_METHOD'] == 'POST' && array_key_exists('fromPerson', $_POST)
{
// logic
}
But there are some cases depends on your logic where isset() and empty() can be good as well.
In that case using method isset is not appropriate.
According to PHP documentation: http://php.net/manual/en/function.array-key-exists.php
(see Example #2 array_key_exists() vs isset())
The method array_key_exists is intended for checking key presence in array.
So code in the question could be changed as follow:
function fromPerson() {
if (array_key_exists('fromPerson', $_POST) == FALSE) {
return '';
} else {
return '+from%3A'.$_POST['fromPerson'];
};
}
$newString = fromPerson();
Checking presence of array $_POST is not necessary because it is PHP environment global variable since version 4.1.0 (nowadays we does not meet older versions of PHP).
All the methods are actually discouraged, it's a warning in Netbeans 7.4 and it surely is a good practice not to access superglobal variables directly, use a filter instead
$fromPerson = filter_input(INPUT_POST, 'fromPerson', FILTER_DEFAULT);
if($fromPerson === NULL) { /*$fromPerson is not present*/ }
else{ /*present*/ }
var_dump($fromPerson);exit(0);
Try
if (isset($_POST['fromPerson']) && $_POST['fromPerson'] != "") {
echo "Cool";
}
I would like to add my answer even though this thread is years old and it ranked high in Google for me.
My best method is to try:
if(sizeof($_POST) !== 0){
// Code...
}
As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.
You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.
$_POST always exists in itself being either empty or has array values.
$_POST['value'] may not exist, thus throwing an "undefined index" error.
Try isset($_POST['fromPerson'])?
if (is_array($_POST) && array_key_exists('fromPerson', $_POST)) {
echo 'blah' . $_POST['fromPerson'];
}
if( isset($_POST['fromPerson']) ) is right.
You can use a function and return, better then directing echo.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
I recently came up with this:
class ParameterFetcher
{
public function fetchDate(string $pDate):string{
$myVar = "";
try{
if(strlen($_POST[$pDate]) > 0){
$myVar = $_POST[$pDate];
}
}catch (Exception $faild){
die("field NULL or not set for $pDate");
}
[ ... other stuff ]
to fetch a date obviously, but it can take ANY post param. You can also check for GET this way.