Can Someone tell me what's wrong with this code
function someFunction($num=null) {
return $num;
}
if ($name = someFunction('mystr') && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
Why it is going in else condition and giving me notice of undefined variable $name
Edited: - if i do like this
if($name = someFunction() && $name ){
echo 'hello';
} else {
echo 'hi';
}
this time its also going on else condition as it should but it also not showing the error as i understand it, php just check my first condition $name = someFunction() and its fail then just else
but if i do as i do previously $name = someFunction('str') now $name is set so why notice of undefined variable
sorry for bad grammer
just want to know what is happening here.
It's because logical operators like && have higher precedence than the assignment operator =. You can read more about this here: http://php.net/manual/en/language.operators.precedence.php
The line
if ($name = someFunction('mystr') && $name ) {
is being evaluated like this:
if ($name = (someFunction('mystr') && $name) ) {
where the expression in the inner brackets is evaluated first. Because $name has not been defined before this point, a notice is raised.
I think what you're trying to do is this:
if (($name = someFunction('mystr')) && $name ) {
where you assign the value mystr to $name and then also evaluate that it's "truthy". But as pointed out in the comments, this is a bit of a strange approach. The following code would be equivalent:
$name = 'mystr';
if ($name) {
...
This feels a bit like a problem that's been cut down a bit too much in order to explain it, because it's not really clear why you're doing this.
you code output : hi becuase there is $name is in second is always null.
function someFunction($num=null) {
return $num;
}
$name = someFunction('mystr');
if ($name && $name ) {
echo 'hello ';
}else {
echo 'hi';
}
output : mystr && mystr = 1 then output is hello
You haven't assigned anything to your variable $name and since it is an AND Condition, the first gets true but the second one doesn't so assign any value to your $name and add a condition for it to work.
Related
I have two primary variables that are composed of strings and other variables. I want the two primary variables only to be echo'ed if all the variables that they are comprised of have data.
The two primary variables are $introduction and colortxt.
$introduction is comprised of $finalvehicle3, $bodystyle, $mileage, and $hi.
$colortxt is comprised of $model, $exterior, and $interiorspec.
If any of the secondary variables are empty, I don't want the primary variable to be displayed.
Below is the code I have created that doesn't seem to be working. I have been using empty().
My PHP:
<?php
$finalvehicle3 = "Toyota Camry";
$bodystyle = "sedan";
$mileage = "30,000";
$hi = null;
$model = "Camry";
$exterior = "red";
$interiorspec = "black cloth";
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
echo "<textarea name='' id='' style='width: 565px;' rows='8' cols='60'>";
echo $introduction." ".$colortxt;
echo "</textarea>";
echo "<br><br>";
?>
In this case $introduction should not be displayed as $hi = null
I can't get empty([$finalvehicle3, $bodystyle, $mileage, $hi]) to work.
I was able to use:
if (empty($hi)
|| empty($finalvehicle3)
|| empty($bodystyle)
|| empty($mileage)){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle."
with ".$mileage." miles.";
}
Will that not work?
Check if both variables are not empty echo them out:
if (!empty($introduction) && !empty($colortxt)) {
echo $introduction." ".$colortxt;
}
As a side, while coding style has personal preference, where you set these variables seems awkward as you set them to empty based on a condition, but logically (my logical at least) is to instead preset them to empty and add data if the data exists.
INSTEAD of your code here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Do this:
$introduction = "";
$colortxt = "";
if (!empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true) {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (!empty([$model, $exterior, $interiorspec]) == true) {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Just looks cleaner to me :)
I'd also not create a new array to check multiple variables, and would do:
if (
!empty($finalvehicle3)
&& !empty($bodystyle)
&& !empty($mileage
&& !empty($hi)
) {
To clarify (not intended to take away from the other answers); only isset() can accept multiple comma-separated values, and not empty().
The manuals state:
on empty():
bool empty ( mixed $var )
on isset()
bool isset ( mixed $var [, mixed $... ] )
Therefore you need to separate and check if each value is empty.
I.e.:
if(empty($var1)) && empty($var2)){}
Or using the || (OR) logical operator depending on what you want to check for; if any or all are empty.
http://php.net/manual/en/language.operators.logical.php
Note:
What you used here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true)
theoretically would be a "false positive".
If anything, you will need to use the == true in a separate statement.
I.e.:
if(empty($var1)) && empty($var2) && $x_var == true){}
However, the first 2 would need the ! negation operator since you're checking if something is true.
I.e.:
if(!empty($var1)) && !empty($var2) && $x_var == true){}
I try to do this:
if ($var !== ""){
$message = "whatever";
}
But end up having to do this:
if ($var == ""){
//do nothing
} else {
$message = "whatever";
}
Why does that happen? Shouldn't both of those mean the same thing?
!= and == are opposites (non-strict comparison operators).
!== and === are opposites (strict comparison operators, where the value must match what you are comparing exactly).
If you use != instead of !==, your code should work. But:
You should understand what the actual value of your variable is - it's not an empty string. You can use print_r( $var ); to see it.
It's better to use the strict comparison operators === and !==, because they have well-defined behavior that is easier to remember and debug.
As $var is really string just use:
if ($var){//any non-empty string will work fine as it will be casted to boolean automatically
$message = "whatever";
}
$var could be != '' but not= '' eg .. null
if ($var == ""){
//do nothing
} else {
if (is_null($var) {
$message ='NULL';
} else {
$message = "whatever";
}
}
I want to declare a variable in a if statement and use it in the same statement. Is this simply not possible?
Example of problem (not actual use case though...):
if ($test = array('test'=>5) && $test['test'] === 5) {
echo 'test';
} else {
echo 'nope';
}
Error message:
NOTICE Undefined variable: test on line number 6
Because of Operator Precedence you will need to group the assignment with ():
if ( ($test = array('test'=>5)) && $test['test'] === 5) {
echo 'test';
} else {
echo 'nope';
}
A simple use case might be:
if ( ($parts = parse_url($url)) && $parts['port'] == 8080) {
// do stuff
}
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 have the following select list:
<form action="mail.php" method="POST">
<select name="foo" id="foo">
<option value="sales">Sales</option>
<option value="salesAssist">Sales Assist</option>
<option value="billing">Billing</option>
<option value="billingAssist">Billing Assist</option>
</select>
</form>
I need to route the $mailTo variable depending on which option they select, Sales and Sales Assist go to sales#email.com, while Billing and Billing Assist go to billing#email.com.
PHP pseudeo code!
<? php
$_POST['foo'] if inArray(sales, salesAssist) foo="sales#email.com";
else if inArray(billing, billingAssist) foo="billing#email.com";
mailTo="foo"
?>
I know there is nothing correct about the above, but you can see what I am trying to do, change a variable's value based on the selected value. I don't want to do this with JavaScript, I would rather learn more PHP here.
Your pseudocode is pretty much right on. Here is an implementation, using in_array():
if (in_array($_POST['foo'], array('sales', 'salesAssit')) {
$foo = 'sales#email.com';
}
elseif (in_array($_POST['foo'], array('billing', 'billingAssit')) {
$foo = 'billing#email.com';
}
Of course, there are other ways to go about this. With only two values to search for, you could also do something like this:
if ($_POST['foo'] == 'sales' || $_POST['foo'] == 'salesAssit') {
$foo = 'sales#email.com';
}
elseif ($_POST['foo'] == 'billing' || $_POST['foo'] == 'billingAssit') {
$foo = 'billing#email.com';
}
Or, just check for the occurrence of the 'billing' or 'sales', using strpos():
if (strpos($_POST['foo'], 'sales') !== false) {
$foo = 'sales#email.com';
}
elseif (strpos($_POST['foo'], 'billing') !== false) {
$foo = 'billing#email.com';
}
However, what I like to do in situations like these, where you know it will always be one option or the other, is assign one as the default, and only change it if necessary:
$foo = 'sales#email.com';
if (strpos($_POST['foo'], 'billing') !== false) {
$foo = 'billing#email.com';
}
Try :
function startsWith($haystack, $needle) {
return $needle === "" || strpos($haystack, $needle) === 0;
}
if(startsWith($_POST["foo"], "sales") {
$foo = "sales#email.com";
} else if(startsWith($_POST["foo"], "billing") {
$foo = "billing#email.com";
}
Keep it simple, sir by using and array of e-mail values which you then cross check with array_key_exists.
// Set an array of e-mails.
$email_array = array();
$email_array['sales'] = "sales#email.com";
$email_array['salesAssist'] = "sales#email.com";
$email_array['billing'] = "billing#email.com";
$email_array['billingAssist'] = "billing#email.com";
// Do basic checks on 'foo'. If not? It's null.
$foo = isset($_POST['foo']) && !empty($_POST['foo']) ? $_POST['foo'] : null;
// Now check if 'foo' is in the array. If not? It's null.
$mailTo = !empty($foo) && array_key_exists($foo, $email_array) ? $email_array[$foo] : null;
The benefit of doing it this way is it’s clean & simple. You can set any e-mail you want in the array. And you can even set a default—instead of null—if you wish if somehow the script gets returned with none of the options selected.
Or if ternary logic seems confusing & you would rather just act on the data right away, this will work:
// Do basic checks on 'foo'. And check if 'foo' is in the array. If not? It's null.
$mailTo = null;
if ((isset($_POST['foo']) && !empty($_POST['foo'])) && array_key_exists($_POST['foo'], $email_array)) {
$mailTo = $email_array[$foo];
}