I have an if statement which is the below one. But its not working i dont know the reason.
if ((($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) && $posted['pref_sal_prd'] != -1) || $posted['pref_sal_optn'] != -1){
// Success code
} else {
// Else Part
}
What's wrong in my code?
Here I need either one in first two, and if either one is not empty than the third one should be compulsory.
if these three should be true or the fourth one is true like this.
EDIT :
array(4) { ["pref_sal_brn"]=> string(3) "234" ["pref_sal_end"]=> string(3) "500" ["pref_sal_prd"]=> string(2) "47" ["pref_sal_optn"]=> string(2) "51" }
this is the output, first two parameters are salary begin and end, thrid one is period option like day, month, weekly,
and the fourth one is some options like , negotiable, minimum wage, like that. so first two are integers, third fourth are drop down lists for the items.
Just tested your code in phpfiddle.org and it is working properly. it will print success as it is supposed to
`
$posted['pref_sal_brn'] = "234";
$posted['pref_sal_prd'] = "47";
$posted['pref_sal_end'] = "500";
$posted['pref_sal_optn'] = "51";
if (( ($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) && $posted['pref_sal_prd'] != -1) || $posted['pref_sal_optn'] != -1) {
echo 'success';
} else {
echo 'failure';
}
?>
This answer is based on what i understand while reading and analyzing your question, Your question is kinda hard to understand but this is what i grasp so far. Correct me if im wrong
Based on my understanding you cannot have it with one liner condition. you might want to break them into separate ifs
You said:
I need either one in first two(pref_sal_brn and pref_sal_end), and if either one is not empty
then the third one should be compulsory. (do this if above is true)
if these three should be true (I understand this that 1 and 2 above should be true)
or the fourth one is true like this. (or if the fourth one is true then whole process is true)
Breaking them and turning them into code:
// CHECK FIRST IF THE pref_sal_optn is TRUE, IF IT IS TRUE THEN DISREGARD OTHER CONDITION
if ($posted['pref_sal_optn'] != -1) {
// success
}
// NOW CHECK IF pref_sal_brn OR pref_sal_end IS NOT NULL
elseif ($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) {
// YOU DISCOVERED THAT EITHER ONE OF pref_sal_brn OR pref_sal_end IS NOT NULL THEN CHECK IF pref_sal_prd IS != -1 IF TRUE THEN DO SUCCESS AGAIN
if ($posted['pref_sal_prd'] != -1) {
// success
} else {
// error
}
} else {
// error
}
Related
I am writing a rostering app. This statement checks that by booking an extra shift the user doesn't violate a rule whereby they have booked more than 7 night shifts in a row. This code runs fine but I am trying to find a more elegant way to write it, for instance using a for loop within the if statement. This snippet exists within a bigger while loop.
if (
$original_shift->night_shift==true &&
$p_lookback_night_7===[1,1,1,1,1,1,1] || $p_lookforward_night_7===[1,1,1,1,1,1,1] ||
($p_lookback_night_1===[1] && $p_lookforward_night_6===[1,1,1,1,1,1]) ||
($p_lookback_night_2===[1,1] && $p_lookforward_night_5===[1,1,1,1,1]) ||
($p_lookback_night_3===[1,1,1] && $p_lookforward_night_4===[1,1,1,1]) ||
($p_lookback_night_4===[1,1,1,1] && $p_lookforward_night_3===[1,1,1]) ||
($p_lookback_night_5===[1,1,1,1,1] && $p_lookforward_night_2===[1,1]) ||
($p_lookback_night_6===[1,1,1,1,1,1] && $p_lookforward_night_1===[1])
) {
return 'You can\'t do more than 7 night shifts in a row';
break;
}
The $p_look variables get populated by a loop looking either back of forward the specified number of days at the end of the variable name and returning an array of true or false for that number of days dependent on whether those are night shifts or not.
As an alternative to building several arrays and complex comparisons, this alternative just uses 2 arrays, one with the days prior and one looking forward. I'm not 100% sure if this includes the day they are trying to book off, but hopefully the idea is easy enough to adjust to your needs.
The basic concept is to look backwards through the $p_lookback_night list and count the 1's, stopping when it reaches a 0. It then does a similar thing through the $p_lookforward_night list. The end result is the number of 1's in a row...
$p_lookback_night = [0,0,0,0,1,1];
$p_lookforward_night = [1,1,1,1,0,0];
$run = 0;
foreach (array_reverse($p_lookback_night) as $test ) {
if ( $test == 1 ) {
$run++;
}
else {
break;
}
}
foreach ($p_lookforward_night as $test ) {
if ( $test == 1 ) {
$run++;
}
else {
break;
}
}
echo $run;
With the test data it gives 6, so you can use this to decide if they are trying to book 7 in a row.
Assuming all those arrays can only contain 1 in this case you can simply just count the values
&& count($p_lookback_night_7)===7 || ...
Maybe even use the int at the end dynamically but this will be probably more trouble that it is worth. Something like
for($i=1;$i<8;$i++){
if(count(${"p_lookback_night_".$i}) == $i && count(${"p_lookforward_night_".$i}) == $i ){
..wahtever
}
}
I have an implemented control check on a form coded this way:
public function checkCittaResidenza() {
if (is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45 || strlen($this->citta_residenza == 0))) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
}
In this version, it simply checks if it is a string and check its lenght that should be less than 45 chars. It puts the string in an array corretti() if positive, else it initialize an error message specified above in an abstract class parent of the checking class.
What i'd love it to do is:
1) make a check on the string to see if it's not null.
2) if it's not null, do the check (that could be even more particular than the simple one shown here, but i don't have problems on this), put it in corretti() if correct and initializing the error if it's not, as the code now says.
3) if the string is null, the program should skip the check and directly write the null value into the array corretti(), because the form is imagined to be completed in different steps over the time, so it always happen that it's not fully filled.
I'm having problem on coding the if cycle for this last condition, every cycle i tried and imagined puts the empty condition as a cause for initializing an error.
Thank you!
Try this,
public function checkCittaResidenza() {
if(isset($this->citta_residenza)){
if ((is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45) || $this->citta_residenza == "")) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
} else {
$this->corretti['citta_residenza'] = "null";
}
}
I have eight input fields in my form that I need to check whether they are empty. Four of these are text fields, the other four are list boxes. When the user submits the form, the four text boxes need to be filled. The fifth field is a Yes/No selection. If the selection in this field is "No", then the remaining three can be left blank. However, if the selection in the fifth field is "Yes" then the last three also have to be selected using the list boxes.
Let us call the first four (textboxes) "mandatory-text1", "mandatory-text2", "mandatory-text3", and "mandatory-text4", the Yes/No selection list box "yes-no" and the optional selections "a", "b" and "c".
SO:
If mandatory-text1, or mandatory-text2, or mandatory-text3, or mandatory-text4, are blank, the processing php will abort.
However, if mandatory-text1, mandatory-text2, mandatory-text3, and mandatory-text4, are all filled in, the next check is to see whether the yes-no contains a "Yes" or a "No".
If it contains a No, then a, b and c have to be necessarily left
blank.
If it contains a Yes, then a, b and c (list boxes) have to be
necessarily selected.
With my level of proficiency in PHP, I have been able to reach this far:
if ((mandatory-text1 || mandatory-text2 || mandatory-text3 == "") OR (yes-no == "Yes" AND (!(a || b || c == ""))) {
echo "blah" ;
exit();
}
else {
//do some stuff
}
I haven't coded the 'do some stuff' part yet because when I try this code, I get the 'blah' message even when all the text fields are filled in, the yes-no is "Yes" and a, b and c have been selected.
I tried it first with a simple "||" for all the fields and that works fine - i.e. if even one of the fields is left blank I get the 'blah' message. I have also tried just checking for the yes-no and a,b,c and that too works fine i.e. if there is a Yes in the yes-no i get the blah if the a,b,c fields are blank.
But I need to satisfy all the conditions before I can proceed to the next step. The posts I have read here on SO brought me to the stage I am in right now. But none went to the level I want for my project.
Any hints for the logic would be appreciated!
Okay first of all, you are supposed to use $ before variable names
Second,
mandatory-text1||mandatory-text2||mandatory-text3==""
is wrong logic. It should be $mandatory-text1=""||$mandatory-text2==""|| ...
It works because if(mandatory-text1) alone means if mandatory-text1 is defined and not empty or null string, so in this case $mandatory-text1||$mandatory-text2||$mandatory-text3 alone is sufficient
if ((mandatory-text1 || mandatory-text2 || mandatory-text3 == "") OR (yes-no == "Yes" AND (!(a || b || c == ""))) {
echo "blah" ;
exit();
}
else {
//do some stuff
}
same for a||b||c
(mandatory-text1 || mandatory-text2 || mandatory-text3 == "")
This isn't working the way you think it is. This says:
if mandatory text 1 is not empty or mandatory 2 text is not empty or mandatory 3 text is equal to ''.
Try:
(mandatory-text1 == "" || mandatory-text2 == "" || mandatory-text3 == "")
You may redesign your control in a more readable way, with a function or code block per field type, for example :
<?php
function checkFields( $data )
{
// List of field to check
$fields = array( 'mandatory-text1', 'mandatory-text2', 'mandatory-text3', 'mandatory-text4', 'a', 'b', 'c' );
foreach ($fields as $field )
{
switch( $field )
{
case 'mandatory-text1':
case 'mandatory-text2':
case 'mandatory-text3':
case 'mandatory-text4':
if ( $data[$field] == '' )
{
return false;
}
break;
case 'a':
case 'b':
case 'c':
if ( $data['yes-no'] == 'yes' && $data[$field] == '' )
{
return false;
}
elseif( $data['yes-no'] == 'no' && $data[$field] != '' )
{
return false;
}
break;
}
}
// If we have not returned false so far, then all is clear
return true;
}
// Usage :
if( checkFields( $_POST ) )
{
// every thing is ok
}
else
{
// bad submission
}
?>
You should mostly avoid 2 things here :
Long AND / OR statements
Repeating your self with the smae controls
If I understood correctly, something like this should work. Do NOT use dashes in variable names.
if ($mandatory1 && $mandatory2 && $mandatory3 && $mandatory4)
{
if ($choice == "Y" && $a && $b && $c)
{
// do whatever
}
elseif ($choice == "N" && !$a && !$b && !$c)
{
// do something else
}
}
else
{
// submission incorrect
}
I need to get the last non-empty value that $_GET['id_item'] had
session_start();
if(!isset($_SESSION['id_item']) || $_SESSION['id_item']==='' || ( isset($_GET['id_item']) && !$_GET['id_item'] === '' )){
$_SESSION['id_item'] = $_GET['id_item'];
}else{
/*no need to update*/
}
echo $_SESSION['id_item'] /* Allways in blank :S */
And var_dump($_GET) outputs:
array(1) { ["id_item"]=> string(2) "50" }
Any idea why the $_SESSION is not saved?
fix this:
$_SESSION['id_item']=='' to $_SESSION['id_item']===''
or you can use:
empty($_SESSION['id_item'])
unless you expect a (valid) ID to be 0 you can reduce !isset($_SESSION['id_item']) || $_SESSION['id_item']==='' to empty($_SESSION['id_item']). !$_GET['id_item'] === '' is always false, as this translates to false === ''. You were probably looking for $_GET['id_item'] !== ''. Again, if 0 is not a valid value, you can go for !empty($_GET['id_item']) here.
That said, the whole !isset($_SESSION['id_item']) || $_SESSION['id_item']==='' part of the condition doesn't make much sense. The second part "if _GET id_item present" is always necessary for the condition's body ($_SESSION['id_item'] = $_GET['id_item'];) to work. So you can reduce your condition to
<?php
if (!empty($_GET['id_item'])) {
// import new id_item
$_SESSION['id_item'] = $_GET['id_item'];
} elseif (!isset($_SESSION['id_item'])) {
// make sure we don't run into an undefined array index notice
$_SESSION['id_item'] = null;
}
var_dump($_SESSION['id_item]);
Have you output anything before the start_session. If so it will be unable to send the cookie. This is probably why it is not working.
I want to check if a query variable exists or not. Then I would do something based on that query value. If it exists and is true, do something. If it doesn't exist or is false, do something else such as show a 404 page.
e.g If the url was domain.com?konami=true
if (condition) {
//something
} else {
//show404
}
OPs question is a bit unclear. If you assume that he wants to check that konami is a $_GET parameter and that it has the value of "true" do:
if (isset($_GET["konami"]) === true && $_GET["konami"] === "true") {
// something
} else {
// show 404
}
The problem with the current accepted answer (by Cameron) is that it's lacking the isset check (which is unforgivable, it is objectively wrong). The problem of the highest voted answer (by Jan Hancic) is that it lacks the === "true" check (which is debatable, it depends on how your interpret the question).
Note that && is a lazy-and, meaning that if the first part is false, the second part will never be evaluated, which prevents the "Undefined index" warning. So the order of the statements is important.
Also note that $a === true is not the same as $a === "true". The first compares a boolean whereas the second compares a string.
If you do weak comparison $a == true you are checking for truthy-ness.
Many values are truthy, like the string "true", the number 1, and the string "foo".
Examples of falsy values are: empty string "", the number 0 and null.
"true" == true; // true
"foo" == true; // true
1 == true; // true
"" == true; // false
0 == true; // false
null == true; // false
"true" === true; // false
"true" === false; // false
There is a little confusion around what value should be tested. Do you want to test the konami parameter for being true in the sense of boolean, i.e. you want to test konami parameter for being truthy, or do you want to test if it has string value equal to "true"? Or do you want to test konami parameter for any value in general?
I guess what is wanted here is to test konami for a given string value, "true" in this case, and for being set at the same time. In this case, this is perfectly enough:
ini_set('error_reporting', E_ALL & ~E_NOTICE);
...
if ($_GET['konami'] == "true")
...
This is enough, because if the $_GET['konami'] is unset, it cannot be equal to any string value except for "". Using === is not neccessary since you know that $_GET['konami'] is string.
Note that I turn off the E_NOTICE which someone may not like - but these type of "notices" are normally fine in many programming languages and you won't miss anything if you disable them. If you don't, you have to make your code unecessarily complex like this:
if (isset($_GET['konami']) && $_GET['konami'] == "true")
Do you really want to complicate your code with this, or rather make it simple and ignore the notices like Undefinex index? It's up to you.
Problems with other answers as you mentioned:
#Jan Hancic answer: it tests for true, not "true".
#Cameron answer: might be simplified and he didn't mention the necessity of disabling E_NOTICE.
#Frits van Campen's answer: too complex to my taste, unnecessary test for === true
Umm this?
if (isset($_GET['konami']) === true) {
// something
} else {
//show 404
}
Easy:
if(isset($_GET['konami']) && $_GET['konami'] != 'false') {
//something
} else {
// 404
}
quick and simple.
$konami = filter_input(INPUT_GET, 'konami', FILTER_VALIDATE_BOOLEAN) or die();
ref:
filter flags
filter_input
You may try this code. In this code checked two conditions by one if condition that is $konami contains value and $konami contains 'true'.
$konami = $_GET['konami'];
if( ($konami) && ($konami == "true")){
/*enter you true statement code */
}else {
/* enter your false statement code */
}
You can do it like this:
$konami = false;
if(isset($_GET['konami'])){
$konami = $_GET['konami'];
}
if($konami == "true"){
echo 'Hello World!';
}
else{
header('HTTP/1.0 404 Not Found');
}
In this case you'll always have $konami defined and - if set - filled with the value of your GET-parameter.
if(!$variable) {
//the variable is null
die("error, $variable is null");
}else{
//the variable is set, your code here.
$db->query("....");
}
This works best:
$konami = $_GET['konami'];
if($konami == "true")
{
echo 'Hello World!';
}
else
{
header('HTTP/1.0 404 Not Found');
}
Easiest and shortest way of doing it:
if($konami != null){ echo $konami; } else { header('HTTP/1.0 404 Not Found'); }