If not or statements - php

Very simple question... I'm having an issue that an if statement isn't working? All I want is the statement to be that if when $quantity is not equal to 20, or 40, or 80, or 160 to display here.
if($quantity != '20' || $quantity !='40' || $quantity != '80' || $quantity != '160')
{
echo "here";
}
Any suggestions would be appreciated. :)

Try this, it's cleaner (IMO) :
if (!in_array($quantity, array(20, 40, 80, 160))
{
echo "here";
}
Else just replace || with &&.

replace the || (or) by && (and) ;)
This way you check if something is 20, then you check if something is 40, etc. So when you have for example 40 the first check (!=20) just returns True (since you are using or's) and it never reaches the second or further check.

If $quantity is 40, it is not 20, so the condition is satisfied.
Study and understand http://en.wikipedia.org/wiki/De_Morgan%27s_Law .

If you don't want $quantity to be equal to any of them, you need to change your '||' or operator to the and operator '&&'.

I made it easier to check for higher numbers, by figuring out your algorithm.
Iterative:
<?php
for ($i = 0; $i <= 3; $i++) {
if ($quantity == pow(2,$i)*20) { echo "not here"; goto matched; }
}
echo "here";
matched:
?>
More functional:
<?php
if (!in_array($quantity,
array_map(
function ($i) { return pow(2,$i)*20; },
range(0,3)
)
)) {
echo "here";
} else {
echo "not here";
}
?>

Related

Any way to shorten this if statement? PHP

I'm trying to keep my code nice and elegant. Any way to make this if statement shorter?
if(strlen($cname) > 100) {
}
if(strlen($cowner) > 100) {
}
if(strlen($cemail) > 200) {
}
if(strlen($cpassword) > 100) {
}
I can't do this because I want to print out a specific message for each if statement:
if(strlen($cname) > 100 || strlen($cowner) > 100 || strlen($cemail) > 200 || strlen($cpassword) > 100) {
// I want to print out a message like email is too long not just one of these strings is too long
}
Frankly, I think you've got the most elegant solution for what you are trying to do.
You can use a loop to reduce the number of lines. Here is an optimized solution even when you have more 10 fields to check:
Declare an array of fields and loop through it
$fields = array("cname" => 100, "cowner" => 100, "cemail" => 200, "cpassword" => 100); // key as field name and value as maximum limit - new values can be added here.
foreach($fields as $field => $length) {
if(strlen(${$field}) > $length) {
die("$field field can only contain $length characters");
}
}
Edit: You can also keep all errors in an array and then print all the errors on your page.
$errors = array();
foreach($fields as $field => $length) {
if(strlen(${$field}) > $length) {
$errors[] = "$field field can only contain $length characters";
}
}
print_r($errors);
You already using an optimized code. But you can optimize it little bit more for showing error message. Like below:
$invalidFieldName = '';
$invalidFieldLength = 100;
if (strlen($cname) > 100) {
$invalidFieldName = 'CNAME';
} elseif (strlen($cowner) > 100) {
$invalidFieldName = 'COWNER';
} elseif (strlen($cemail) > 200) {
$invalidFieldName = 'CEMAIL';
$invalidFieldLength = 200;
} elseif (strlen($cpassword) > 100) {
$invalidFieldName = 'CPASSWORD';
}
if ($invalidFieldName != '') {
echo $invalidFieldName." should be greater than ".$invalidFieldLength;
}
I am not really sure if it will help you but I hope it will help you.

How to make simple if statement bubble style?

How make this if-statement more simple ? , as a function it's working well but i think it's not good on coding.
this is the code :
if (empty($checkMaxID))
{
$this->model->insert_temp_code($code_request,$cabang_code);
}
$checkHasTempCode = $this->model->checkHasTempCode($user_id);
if ($checkMaxID['tempcode_created_by'] != $user_id ) {
$data['code_request'] = str_pad($checkMaxID['tempcode_value'] + 1, 5, 0, STR_PAD_LEFT);
if (empty($checkHasTempCode) ) {
$this->model->insert_temp_code($data['code_request'],$cabang_code);
}
}
else
{
$data['code_request'] = $code_request;
}
`
anyone can help me please ?
Thank you
Use ternary operator when you have if else condition. Also, you can avoid nested if thorough multiple conditions in a single if statements. I hope this will helps.
$checkHasTempCode = $this->model->checkHasTempCode($user_id);
if (empty($checkMaxID)) {
$this->model->insert_temp_code($code_request,$cabang_code);
}
$data['code_request'] = ( $checkMaxID['tempcode_created_by'] != $user_id ) ?
str_pad($checkMaxID['tempcode_value'] + 1, 5, 0, STR_PAD_LEFT) : $code_request;
if ( empty($checkHasTempCode) && $checkMaxID['tempcode_created_by'] != $user_id ) {
$this->model->insert_temp_code($data['code_request'],$cabang_code);
}

PHP if not null then

I have the following code but really instead of matching the strings, I really want to do if $line, 88, 30 is not null then $status = "delivered";
if (preg_match("/pod/i", $filename)) {
if (substr($line, 88, 30) == 'SOMETHING') {
$status = "delivered";
} else {
continue;
}
}
else {
...
}
Am I right in thinking that I should wrap the substr() with an isset() or should I be using empty() ? I think I'm getting confused which way round it should go?
$line is below I only want to change status to delivered if a name exists
CUSTPOD1.003123797001868810003660228092015102800Mark
CUSTPOD1.003123797001867710003660128092015095700
I managed to get it to work with the following code, by storing the string in a var first I was then able to trim it and then use !empty (not empty) to check for characters
if (preg_match("/pod/i", $filename)) {
$somevar = trim(substr($line, 88, 2));
if (!empty($somevar)) {
$status = "delivered";
} else {
continue;
}
} else {

Please help! How to express the cases in if clause?

I have string $a,$b,$c
I know if all of them not null express in this way:
if($a!="" && $b!="" && $c!="")
But if either 2 of them not null then go into the true caluse
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(either 2 are not null){
**do another things here**
}
How to express it?
I would write a simple function like this to check:
function checkInput($var)
{
$nulls=0;
foreach($var as $val)
{
if(empty($val))
{
$nulls++;
}
}
return $nulls;
}
Then access it like this:
$inputs=array($a, $b, $c.... $z);
$nullCount=checkInput($inputs);
if($nullCount==0)
{
// All nulls
}
if($nullCount>2)
{
// More than 2 nulls
}
or for an one-off test, just pop the function into the actual if statement like this:
if(checkInput($inputs)>2)
{
// More than 2 nulls...
}
etc etc. You can then use the one function to check for any number of nulls in any number of variables without doing much work - not to mention change it without having to rewrite a long if statement if you want to modify it.
Other answers are good, but you can expand this to easily handle more variables:
$variables = array($a, $b, $c, $d, ....);
$howManyNulls = 0;
foreach($variables as $v){
if($v == ''){
$howManyNulls++;
}
}
if($howManyNulls == count($variables) - 2){
// do stuff
}
you can try this
if($a!="" && $b!="" && $c!="")
{
** do the things here **
}
else if(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!=""))
{
**do another things here**
}
Try:
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(($a!="" && $b!="") || ($a!="" && $c!="") || ($b!="" && $c!="")){
**do another things here**
}
$var[] = empty($a) ? 0:$a;
$var[] = empty($b) ? 0:$b;
$var[] = empty($c) ? 0:$c;
$varm = array_count_values($var);
if ($varm[0] === 0) {
//Code for when all aren't empty!
} elseif ($varm[0] === 1) {
//Code for when two aren't empty!
}
N.B; You may need to replace the 0 for a string/integer that will never crop up, if your variables are always strings or empty then 0 will do for this. The method for using bools within this would require more code.
$nullCount = 0
if($a!=""){ ++$nullCount; }
if($b!=""){ ++$nullCount; }
if($c!=""){ ++$nullCount; }
if($nullCount == 3){ // all are null
// do smth
}else if($nullCount == 2){ // only two are null
// do other
}
Just for fun, here's something potentially maintainable, should the list of arguments increase:
function countGoodValues(...$values) {
$count = 0;
foreach($values as $value) {
if($value != "") {
++$count;
}
}
return $count;
}
$goodValues = countGoodValues($a, $b, $c); // Or more... or less
if($goodValues == 3) {
// Do something here
}
else if($goodValues == 2) {
// And something else
}
Reference for the ... construct (examples #7 and #8 in particular) are available on php.net.
You can use double typecasting (to boolean, then to number) in conjunction with summing:
$count = (bool)$a + (bool)$b + (bool)$c;
if ($count == 3)
// ** do the things here **
else if ($count == 2)
//**do another things here**
There is also possible such solution:
<?php
$a= 'd';
$b = 'a';
$c = '';
$arr = array( (int) ($a!=""), (int) ($b!=""), (int) ($c!=""));
$occ = array_count_values($arr);
if ($occ[1] == 3) {
echo "first";
}
else if($occ[1] == 2) {
echo "second";
}
If you have 3 variables as in your example you can probably use simple comparisons, but if you have 4 or more variables you would get too big condition that couldn't be read.
if (($a!="") + ($b!="") + ($c!="") == 2) {
// two of the variables are not empty
}
The expression a!="" should return true (which is 1 as an integer) when the string is not empty. When you sum whether each of the strings meets this condition, you get the number of non-empty strings.
if (count(array_filter([$a, $b, $c])) >= 2) ...
This is true if at least two of the variables are truthy. That means $var == true is true, which may be slightly different than $var != "". If you require != "", write it as test:
if (count(array_filter([$a, $b, $c], function ($var) { return $var != ""; })) >= 2) ...
if($a!="" && $b!="" && $c!="") {
echo "All notnull";
} elseif(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!="")) {
echo "Either 2 notnull";
}

'If' statement with the 'or' operator in PHP

I'm trying to build up a PHP if statement with or ("||") operators, but it doesn't seem to work.
$country_code = "example_country_code";
if ($country_code != 'example_country_code' || !clientIscrawler()) {
echo 'the script can be executed';
}
else {
echo 'skipping';
}
With the given example, it should be echoed skipping, but it doesn't happen like that. What am I doing wrong?
Perhaps the double negatives are giving you problems. Let's rewrite it to:
!($country_code == 'example_country_code') || !clientIscrawler()
This can be turned into an equivalent condition with &&:
!($country_code == 'example_country_code' && clientIscrawler())
By reversing the if you would get this:
if ($country_code == 'example_country_code' && clientIscrawler()) {
echo 'skipping';
} else {
echo 'the script can be executed';
}
Therefore, in your code, it will only print skipping if clientIscrawler() is truthy.
If you have multiple conditions with the OR operator, in which case you don't want the if statement to evaluate as true, the syntax is:
if(!($something == "something" || $something == 'somethingelse')){
do stuff...
}
Here is an example:
$apples = array (
1 => "Pink Lady",
2 => "Granny Smith",
3 => "Macintosh",
4 => "Breaburn"
);
foreach($apples as $apple){
// You don't want to echo out if the apple name is "Pink Lady" or "Macintosh"
if(!($apple == "Pink Lady" || $apple == "Macintosh")){
echo $apple."<br />";
}
}
// Output is:
Granny Smith
Breaburn
In your given code, it all depends on your function call
!clientIscrawler()
You will be getting the script can be executed output only when your function call returns FALSE. I think it is returning TRUE right now, which is why you are not getting the desired output.
Maybe this can help you:
if ( ($country_code != 'example_country_code') || clientIscrawler() == false) {
Try this way:
if ( ($country_code != 'example_country_code') || !clientIscrawler()) { ...

Categories