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){}
Related
Heyo newbie to PHP here,
I'm creating a registration form where the user is able to select how many family members are in the family, Depending on the number selected the same number of fields would be created to allow them to enter family members' details.
The form checks if all error messages are empty before starting the database insert.
I've been trying for hours though still not sure what's causing the array to return empty() - False,
Full Code -
GDrive Share Link
Creation of the Arrays
$MemberNameErr = array();
$MemberDOBErr = array();
Giving the Array values based on the number of Family Members
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter;
$Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
If function that checks that no errors have been made
if ($FamilyNameErr == "" && $DateErr == "" && $EmailErr == "" && $PhoneErr == "" && $MobileErr == "" && empty($MemberNameErr) && empty($MemberDOBErr))
{
currently using empty() as a way to check if the array is empty
created these just to check if the arrays were Not Empty
if (!empty($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (!empty($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}
Thank you for all your input.
In your loop
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter; $Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
You're assigning empty string to indexes of the array. This means the array isn't empty anymore.
In example :
$tab = array("", "", "");
if (empty($tab))
{
echo "Empty";
}
else
{
echo "Not empty";
}
Output :
Not empty
A workaround could be to iterate through this array and check if there's at least 1 non empty string.
In example
function CheckNonEmptyValue($arr)
{
foreach ($arr as $value)
{
if (!empty($value))
{
return (true);
}
}
return (false);
}
if (CheckNonEmptyValue($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (CheckNonEmptyValue($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}
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.
i want to check two string in if condition equal or not but it is give me return true whats the problem please check my code.
$if = "(1 == 2)";
if($if){
echo 'hi';
}
see my code above.. it always return hi.. what i was done wrong please help me.
its return only hi.. i have many condition store in if variable but my first condition not fulfill so i want it now.. please suggest me.
my full code is here..
$if = "(1 == 2)";
if($location_search != ''){
$if .= " && ('."$location_search".' == '."$get_city".')";
}
if($location_state != ''){
$if .= " && ('."$location_state".' == '."$get_state".')";
}
if($location_bedrooms != ''){
$if .= " && ('."$location_bedrooms".' == '."$get_bedrooms".')";
}
if($location_bathrooms != ''){
$if .= ' && ('."$location_bathrooms".' == '."$get_bathrooms".')';
}
if($location_type != ''){
$if .= ' && ('."$location_type".' == '."$get_type".')';
}
if($location_status != ''){
$if .= " && ('".$location_status."' == '".$get_status."')";
}
if($if){
echo 'hi';
}
i added this code but always return tru and print hi. please help me.
Collect all of your variables in one array and go through it with foreach checking everyone. If one of variables is empty, assign false to your if variable. Will write code later, when will be next to computer.
Your variable $if is a declared as a string due to the double quotes. How about this
$a = 1;
$b = 2;
if ($a == $b) {
// When $a equals $b
echo "hi";
} else {
// When $a doesn't equal $b
$if is a string, and not null. In PHP this means it's true. I think if you remove the quotes, it should instead evaluate the expression to false.
Remove the double quotes here " (1 == 2)"
You can remove quotes (with quotes it's a normal string), but keep in mind that this is bad approach and should not be used like this.
Working code:
$if = (1 == 2); // evaluates to true
if($if) {
// code
}
So I've got this code and part of it is a form, and ALL fields are absolutely required.
I just can't find clear documentation for my needs to validate everything.
would I do something like this?
$foo = $_POST['foo'];
$bar = $_POST['bar'];
$lorem = $_POST['lorem'];
$ipsum = $_POST['ipsum'];
$isSet = array($foo, $bar, $lorem, $ipsum);
if(isset($isSet)) { /* Do the stuff */ }
or is there a better way? I don't really want to do
if(isset($foo) && isset($bar) && isset($lorem)........
because i've got about 12 fields that are required
You can do:
if (isset($foo, $bar, $lorem, $ipsum)) {.....}
Saves you one step.
http://php.net/manual/en/function.isset.php
Remember that isset will return true if you have an empty string. So, technically
isset($_POST['foo'])
would return true if foo is passed in with a blank value:
foo=&bar=&...etc.
Also,
isset(array())
returns true;
If "" is not a valid value for one of those variables, you will want to do the following:
$requiredFields = array('foo', 'bar', 'lorem', 'ipsum');
$allValid = true;
foreach ($requireFields => $fieldName) {
if (isset($_POST[$fieldName]) && $_POST[$fieldName] != "") {
$allValid = $allValid && true;
} else {
$allValid = $allValid && false;
}
}
if ($allValid) {
//...success...
} else {
//...failed...
}
You essentially check that the variable was passed and also that the variable is not set to "".
Hope that helps.
I'm trying to make an if statement with 2 conditions. One that checks if one variable is NOT present & does NOT matches the word "good2go" and the other that checks to make sure "body" variable is present. I'm trying to trip the error message here. Here is what I have and what I've tried, and none of it seems to work.
if (stripos($_POST['check'], 'good2go') == FALSE && $_POST['body']) {
$error = true; }
if (!$_POST['check'] == 'good2go' && $_POST['body']) {
$error = true; }
if (!stripos($_POST['check'], 'good2go') && $_POST['body']) {
$error = true; }
if ((!stripos($_POST['check'], 'good2go')) && $_POST['body']) {
$error = true; }
How do I get this to work?
here's the entire code of contact_us.php this has the validation code and the email code.
$error = false;
if (isset($_GET['action']) && ($_GET['action'] == 'send')) {
// Winnie the pooh check
//$t = tep_db_prepare_input($_POST['verify']);
if (!isset($_POST['check']) && !$_POST['check']=='good2go' && isset($_POST['body'])) {
$error = true;
} else { // Winnie the pooh Check
$name = tep_db_prepare_input($_POST['name']);
$email_address = tep_db_prepare_input($_POST['email']);
//IP recorder start
$ipaddress = $_SERVER["REMOTE_ADDR"];
$ip = "\n\nIP: " . $ipaddress;
$content = "\n\nName: ".$name."\n\nComments: ".$_POST['enquiry'];
$product = tep_db_prepare_input($_POST['product']);
if ($product) {
$product_text = "\n\nProduct Interest: ".$product; }
$content_ip = $content . $product_text. $ip;
$enquiry = tep_db_prepare_input($content_ip);
//IP recorder end
}
// BOF: Remove blank emails
// if (tep_validate_email($email_address)) {
// tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
// tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// } else {
// $error = true;
// $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
if (! tep_validate_email($email_address)) {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
}
if ($enquiry == '') {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_CONTENT_CHECK_ERROR);
}
if ($error == false) {
tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// EOF: Remove blank emails
}
}
Solution to your updated problem:
if (!isset($_POST['check']) || !$_POST['check']=='good2go' || !isset($_POST['body'])) {
$error = true;
}
The reason for the pipes vs ampersands is that you want to throw an error if ANY of the fields has issue. Also, you want to check if body is NOT set vs IS set. Glad this worked out for you!
and the other that checks to make sure "body" variable is not present.
if(stripos($_POST['check'], "good2go") !== false && !isset($_POST['body'])){
//code here
}
According to PHP docs regarding the stripos function:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So you need to change the first line to:
// Doing stripos checks you MUST use === (not ==)
if (stripos($_POST['check'], 'good2go') !== FALSE && $_POST['body']) {
$error = true; }
And to check if there is no $_POST['body'] you can change the above to:
if (stripos($_POST['check'], 'good2go') !== FALSE && (!isset($_POST['body'])) {
-- Update --
According to your comment, you need $_POST['check'] to equal 'good2go', then you shouldn't be using stripos as it will check for the existence of good2go regardless if it's exactly equal, or part of a string; 'wow this hamburger is good2go'.
So I would change the conditional to:
if (((isset($_POST['body'])) && (strlen($_POST['body']) > 0)) && ((!isset($_POST['check'])) || ($_POST['check'] !== 'good2go'))) {
// Post body has a value and Post check DOES NOT equal good2go, someone is hax0rin!
}
You may want to read up on Cross-site request forgery as it seems right inline with what you are working on.
One that checks if one variable is present & matches the word "good2go"
isset($_POST['check']) AND $_POST['check'] == 'good2go'
and the other that checks to make sure "body" variable is not present.
!isset($_POST['body'])
so, just put them together
if (isset($_POST['check']) AND $_POST['check'] == 'good2go' AND !isset($_POST['body'])) {
$error = true;
}
try this:
if(!empty($_POST['check']) && $_POST['check']=='good2go' && empty($_POST['body'])) { $error=true; }
Consider using empty instead of isset if your $_POST['body'] can be present with an empty value.
No need for all those unneeded functions. What you are trying to achieve is:
if (isset($_POST['check']) && $_POST['check']=='good2go' && !isset($_POST['body']) {
// your code
}
However, As per the title of the question: Use a ternary statement. Syntax is as such
$var = <condition> ? <true> : <false>;