Suppose there are two arrays $a, $b. At any given point at least one of them is not empty or both are not empty.
How do I optimise the following condition
if(!$a)
{
#TASK A
}
if(!b)
{
#TASK B
}
if ($a['item']<$b['item'])
{
#TASK A
}
else
{
#TASK B
}
I don't want TASK A and B to be repeated twice in the program.
if(!$a || ($b && ($a['item'] < $b['item']))){
// task A
}
else{
// task B
}
if(!$a || ($b && ($a['item'] < $b['item']))){
// task A
}elseif(!$b || ($a && ($a['item'] >= $b['item']))){
// task B
}
If the variables may not be set, use empty() or isset()
This will work, but it may not be optimal. But the code is not really clear. Do TaskA and TaskB modify $a and $b?
$aDone = false;
$bDone = false;
if(!$a)
{
#TASK A
$aDone = true;
}
if(!b)
{
#TASK B
$bDone = true;
}
if ($a['item'] < $b['item'])
{
if (!$aDone)
{
#TASK A
}
}
else
{
if (!$bDone)
{
#TASK B
}
}
Related
I am trying to reduce/simplify the following code as it looks to have repeated elements:
<?php
if ($condition == true) {
if ($a > $b*0.5) {
echo "successful";
}
else {
echo "missed";
}
}
else {
if ($a > $b) {
echo "successful";
}
else {
echo "missed";
}
}
I don't want to use functions because if I did, I would have to define all the database things again.
<?php
if ( (condition1 && ($a > $b*0.5)) || (!condition1 && ($a > $b)) ) {
echo "successful";
else {
echo "missed";
}
?>
Your Code is missed Two (Semicoloumns)}.
Try By this
<?php
$a == 2;
$b == 4;
if ($a == 2 && $a > $b*0.5) {
echo "Suuccess";
}elseif($a != 2 && $a > $b){
echo "Suuccess";
}else{
echo "Fails";
}
In order to simplify your conditions, if the output is boolean (so only two outcomes possible) you could go with either one as default and only change it to the other depending on your decisions.
<?php
$outcome = false;
if($condition1 && ($a > ($b * 0.5))) {
$outcome = true;
}
else if($a > $b) {
$outcome = true;
}
if($outcome) {
echo "succesful";
}
else {
echo "missed";
}
This also combines the technique proposed by Sofyan Thayf to use boolean operators to merge conditions.
Another approach is to put the condition into a function and return early if succesful and have a missed fallthrough like
<?php
function decide($a, $b, $condition1) {
if($condition1 && ($a > ($b * 0.5)))
return true;
if($a > $b)
return true;
return false;
}
if(decide($a, $b, $condition1)) {
echo "succesful";
}
else {
echo "missed";
}
Both approaches enable you to extract the "same code" (being the echo) and IMHO add to readability and extensibility.
<?php
$factor = $condition ? 0.5 : 1;
if ($a > $b * $factor) {
echo "Hit";
}
else {
echo "Miss";
}
Could be further reduced using two ternary operators:
echo $a > $b * ($condition ? 0.5 : 1)
? 'Hit'
: 'Miss';
Ternary operators are useful shorthand for if/else conditionals.
I have a PHP file that loads three different pages: a user's followers, following, and their friends (represented below by a, b, and c). Each "page" has different privacy settings depending on who's viewing the website, so a, b, and c have true/false values. If the value is false, then that user cannot view the page. I want to create next and previous buttons, but in order to determine which page is next/previous, I need to factor in the user's privacy. For example, if the user only shows b, there would be no next/previous, but if they showed a, and c, then next/previous for a would be c, and for c it would be a. I wrote some code below that tries to accomplish this, but is there a simpler way to do this without being so repetitious? It's also important that it loop, so even if I'm on page c, the next button will bring me to page a.
$a = $_GET['a']; // true/false
$b = $_GET['b']; // true/false
$c = $_GET['c']; // true/false
$cur = // current page: a, b, or c
if($cur = $a) {
if($b) {
$next = $b;
}
else if($c) {
$next = $c;
}
else {
$next = $a;
}
if($c) {
$previous = $c;
}
else if($b) {
$previous = $b;
}
else {
$previous = $a;
}
}
if($cur = $b) {
if($c) {
$next = $c;
}
else if($a) {
$next = $a;
}
else {
$next = $b;
}
if($a) {
$previous = $a;
}
else if($c) {
$previous = $c;
}
else {
$previous = $b;
}
}
if($cur = $c) {
if($a) {
$next = $a;
}
else if($b) {
$next = $b;
}
else {
$next = $c;
}
if($b) {
$previous = $b;
}
else if($a) {
$previous = $a;
}
else {
$previous = $c;
}
}
UNTESTED
$PRIVACY_PAGES[0] = "followers.php";
$PRIVACY_PAGES[1] = "following.php";
$PRIVACY_PAGES[2] = "friends.php";
function getNextPage($currPageName, $userPrivacy){
//$userPrivacy is array of boolean same order as $PRIVACY_PAGES
$currIdx = getPageIndex($currPageName);
$loopStart = 0;
if($currIdx > -1){
$loopStart = $currIdx+1;
}
if($currIdx == 2){//he is on last page
return "#";
}
for($v=$loopStart;$v<count($userPrivacy);$v++){
if($userPrivacy[$v]==true){
return $PRIVACY_PAGES[$v];
}
}//for loop
return "#";//he have no permission to view any page further.
}
function getPageIndex($currentPageName){
for($p=0;$p<count($PRIVACY_PAGES);p++){
if($PRIVACY_PAGES[0] == $currentPageName)
return $p;
}//for loop
return -1;//he is on another page, like index.php or gallery.php...
}
/////////////
//example :
$userPrivacy[0] = true;
$userPrivacy[1] = false;
$userPrivacy[2] = true;
$next = getNextPage("followers.php", $userPrivacy)
//$next should be friends.php
< html >
:
:
< a href="< ? php echo $next;?>">Next< /a >
an object orientated solution would be clean here, consider this pseudo code:
class page {
private $nextpage;
private $prevpage;
private $permission;
function __construct($nextpage, $permission)
{
$this->nextpage = $nextpage;
$this->permission = $permission;
}
public function GetNextPage($first = $this)
{
if ($this->nextpage == null || $first == $this) {
return false;
} elseif ($this->nextpage->isAllowed()) {
return $this->nextpage;
} else {
return $this->nextpage->GetNextPage($first);
}
}
public function isAllowed()
{
// Some authorization voodoo here
return $_SESSION['userpermissions'] == $permission;
}
}
Same code can be used for previous page. You could even make it dynamic in order to save you redundant code for next and previous.
Now all you have to do is inistantiate each page at the start of your application and you can easily browse through them.
I am doing the following if else statement below but number (//1) and number (//4) get executed at the same time, I am finding it abit hard to understand why.
<?php
//1
if($a == 1 && count($b) == 0) {
// do this
}
//2
elseif ($a == 1 && count($b) > 0) {
// do that
}
//3
if($a== 0 && count($b) == 0) {
// do a different thing
}
//4
else {
// do the last thing
}
?>
I have done this and it works but i think the should be a more suitable way for not using elseif for this.
else if($a== 0 && count($b) > 0) {
// do the last thing
}
but number (//1) and number (//4) get executed at the same time
It's because you don't have else before the if on //3
//3
if($a== 0 &&
Change to elseif($a== 0 &&
At the moment you have two separate IF conditions
You're missing a closing brace after your first if.
Also, you have a weird operator inside your first condition : $$. Maybe you intended to type &&?
$a = 10;
if ($a == 5) {
echo 'ok';
} elseif ($a == 10) { // $a is equal to 10, so it executes;
echo 'not_ok';
}
if ($a > 20) {
echo 'ok_ok';
} else { // $a is not >20 so else statement executes
echo 'not_not';
}
final result: not_oknot_not
If you are performing such tests on one and the same assignee, but different values, you might not want to execute more than one?
I guess you need elseif where third block is if
if ($a == 5) {
echo 'ok';
} elseif ($a == 10) { // $a is equal to 10, so it executes and stops the block;
echo 'not_ok';
} elseif ($a > 20) {
echo 'ok_ok';
} else { // $a is not >20, but the block was stopped on first elseif
echo 'not_not';
}
produces not_ok
Even if you move the else statement after the first elseif block as was suggested
if ($a > 20) {
echo 'ok_ok';
}
will execute, and if it's true, it will produce result, which again will result in double result
You might want to do this...
if ($a == 1 && count($b) == 0) {
// do this
}
//2
elseif ($a == 1 && count($b) > 0) {
// do that
}
elseif ($a== 0 && count($b) == 0) {
// do a different thing
}
else {
// do the last thing
}
The reason they get executed at the same time is that... Well technically they're not executed at the same time since it's procedural, but they both get executed because they are both different if else conditions. If you want only 1 execution, you should combine them :)
I have this code:
If(!isset($a) || empty($a))
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
The issue is that when $a is equal 0 then empty($a) is true and the first code runs. I need the second one to run. How do I do it?
if (isset($a) && $a == 0)
{
//code to run when $a is equal 0
}
elseif (empty($a))
{
// code to run when $a not set or empty;
}
else
{
//code to run in all other scenarios
}
Try this:
if((!isset($a) || empty($a)) && $a !== 0)
{
// code runs when $a not set or empty and $a is not 0;
}
elseif ($a === 0)
{
//code runs when $a is equal 0
}
else
{
//code runs in all other scenarios
}
Update:
Changed to typesafe comparison.
replace this and try
If(!isset($a) || $a=='')
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
I found the solution:
if (!isset($a) || (empty($a) && $a!==0))
{
//run code if $a is not set or is empty
}
elseif ($a===0)
{
//run code if $a is 0;
}
else
{
//all other scenarios
}
Empty function returns false when 0 (0 as an integer).
So your code should be
If(!isset($a))
{
// code to run when $a not set or empty;
}
Elseif ($a==0)
{
//code to run when $a is equal 0
}
Else
{
//code to run in all other scenarios
}
I have an array that could contain any number of values, some of which may recur.
Example: 1,2,2,5,7,3
How can I write a test in PHP that checks to see if the only values contained in the array are either 1 or 2?
So 1,2,2,1,1,1 would return true.
Meanwhile 1,2,3,1,2,1 would return false.
This seems to work just fine:
function checkArray($a)
{
return (bool)!count(array_diff($a, array(1,2)));
}
It'll return true if it's just 1s and 2s or false if not
function return_1_or_2($array){
foreach($array as $a){
$c = $a-1;
if($c>1){
$flag = true;
break;
}
}
if($flag){
return false;
}else{
return true;
}
}
please give this a try... you can further optimise this.... but this is just an example...
function array_contains_ones_and_twos_only( &$array ){
foreach ($array as $x)
if ($x !== 1 && $x !== 2)
return false;
return true;
}
function checkarray($array) {
foreach($array as $a) {
if ($a != 1 && $a != 2)
return false;
}
return true;
}