Several nearly identical if statements need to be shortened - php

So I've got this code...
code:
if(empty($day0[2])) {
echo "<td>".$day0[1]."<br></td>";
} else {
if(strcmp($day0[1],"Absent") == 0) {
echo "<td>".$day0[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day0[1]."<br>Time: ".#$day0[2]." - ".#$day0[3]."</td>";
}
}
if(empty($day1[2])) {
echo "<td>".$day1[1]."<br></td>";
} else {
if(strcmp($day1[1],"Absent") == 0) {
echo "<td>".$day1[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day1[1]."<br>Time: ".#$day1[2]." - ".#$day1[3]."</td>";
}
}
if(empty($day2[2])) {
echo "<td>".$day2[1]."<br></td>";
} else {
if(strcmp($day2[1],"Absent") == 0) {
echo "<td>".$day2[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day2[1]."<br>Time: ".#$day2[2]." - ".#$day2[3]."</td>";
}
}
if(empty($day3[2])) {
echo "<td>".$day3[1]."<br></td>";
} else {
if(strcmp($day3[1],"Absent") == 0) {
echo "<td>".$day3[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day3[1]."<br>Time: ".#$day3[2]." - ".#$day3[3]."</td>";
}
}
if(empty($day4[2])) {
echo "<td>".$day4[1]."<br></td>";
} else {
if(strcmp($day4[1],"Absent") == 0) {
echo "<td>".$day4[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day4[1]."<br>Time: ".#$day4[2]." - ".#$day4[3]."</td>";
}
}
if(empty($day5[2])) {
echo "<td>".$day5[1]."<br></td>";
} else {
if(strcmp($day5[1],"Absent") == 0) {
echo "<td>".$day5[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day5[1]."<br>Time: ".#$day5[2]." - ".#$day5[3]."</td>";
}
}
if(empty($day6[2])) {
echo "<td>".$day6[1]."<br></td>";
} else {
if(strcmp($day6[1],"Absent") == 0) {
echo "<td>".$day6[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day6[1]."<br>Time: ".#$day6[2]." - ".#$day6[3]."</td>";
}
}
Where day 0-6 equals Sunday through Saturday, and the array numbers attached to each one equals a different variable in a multi-dim array.
That is several if statements that are all exactly the same except the variable name inside of each one. I haven't been able to find a way to make this shorter, so I thought I would post here to try and see if anyone has any ideas on how I can combine this into shorter lines of code. I'm all about my code looking neater and functioning better, and I think this could teach a lot of people good ways to shorten their code down a bit.

First merge all array of $day[n] in to $finalArray
foreach($finalArray as $key=>$value){
if(empty($value[2])) {
echo "<td>".$value[1]."<br></td>";
} else {
if(strcmp($value[1],"Absent") == 0) {
echo "<td>".$value[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$value[1]."<br>Time: ".#$value[2]." - ".#$value[3]."</td>";
}
}
}

#MagnusEriksson suggested making a function, I think this is the best way to do it.
From 69 lines of code to 18 lines of code.
function displayTime($day1,$day2,$day3) {
if(empty($day2)) {
return "<td>{$day1}<br></td>";
} else {
if(strcmp($day1,"Absent") == 0) {
return "<td>{$day1}<br>Time: N/A</td>";
}
return "<td>{$day1}<br>Time: {$day2} - {$day3}</td>";
}
}
for ($x = 0; $x <= 6; $x++) {
echo displayTime(${"day$x"}[1],${"day$x"}[2],${"day$x"}[3]);
}

Please try with this code.
$array=array($day0,$day1,$day2,$day3);
for($i=0;$i<count($array);$i++){
if(empty($day.$i[2])) {
echo "<td>".$day.$i[1]."<br></td>";
} else {
if(strcmp($day.$i[1],"Absent") == 0) {
echo "<td>".$day.$i[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day.$i[1]."<br>Time: ".#$day.$i[2]." - ".#$day.$i[3]."</td>";
}
}
}

Related

How to skip to next "elseif" in PHP statement?

If you have an if/else statement like the one below, is there a way to check something inside the first matching if and tell it to skip ahead to the next else/if, and do this multiple times?
continue seemed promising after some googling, but didn't work so maybe that's only for loops
if ($teamscore > 100) {
if ($somethingelse=$something) {
//skip to the next "elseif"
}
} elseif ($teamscore > 95) {
if ($somethingelse=$something) {
//skip to the next "elseif"
}
} elseif ($teamscore > 90) {
} else {
}
It seems like what you're going for is sort of like a switch, but you can't evaluate separate expressions in each case, so you can't use it for inequalities like this. I think this structure could be used instead.
while (true) {
if ($teamscore > 100) {
// DO STUFF
if ($somethingelse != $something) {
break;
}
}
if ($teamscore > 95) {
// DO STUFF
if ($somethingelse != $something) {
break;
}
}
if ($teamscore > 90) {
// DO STUFF
if ($somethingelse != $something) {
break;
}
}
break;
}
However, if // DO STUFF is the same thing in each if block, or a variation of the same thing that fits a pattern, you probably could use a loop instead to avoid the repetition.
for ($score = 100; $score > 85; $score -= 5) {
if ($teamscore > $score) {
// DO STUFF
}
if ($somethingelse != $something) {
break;
}
}
You should turn your condition bodies (in my example, the echo's) into functions:
if ($foo == 'bar') {
echo 'it is bar!';
} elseif ($foo == 'foobar') {
echo 'it is is foobar!';
} else {
echo 'it\'s nada!';
}
becomes:
function sayBar()
{
return 'it is bar!';
}
function sayFooBar()
{
return 'it is foobar!';
}
function sayNada()
{
return 'it\'s nada!';
}
if ($foo == 'bar') {
echo sayBar();
if ($bar == 'Treybake is awesome') {
echo sayFooBar();
}
} elseif ($foo == 'foobar') {
echo sayFooBar();
} else {
echo sayNada();
}
you might be looking for somthing like this,
if ($teamscore > 100 && $somethingelse !== $something) {
} elseif ($teamscore > 95 && $somethingelse !== $something) {
} elseif ($teamscore > 90 && $somethingelse !== $something) {
} else {
}

Can this code be made short using loop? (see detail)

I have to write this whole code for a 10 questions quiz. I compare and prepare results through this code. Is there any solution so that I can type this "if, else if and else conditions" block only once and apply loop on this and get the same results?
$count=0;
$count2=0;
if($ans1==$answer1)
{
$res1= "Correct";
$count=$count+1;
}
else if($answer1=="")
{
$res1="Not attempted";
}
else
{
$res1= "Incorrect";
$count2=$count2-1;
}
if($ans2==$answer2)
{
$res2= "Correct";
$count=$count+1;
}
else if($answer2=="")
{
$res2="Not attempted";
}
else
{
$res2= "Incorrect";
$count2=$count2-1;
}
if($ans3==$answer3)
{
$res3= "Correct";
$count=$count+1;
}
else if($answer3=="")
{
$res3="Not attempted";
}
else
{
$res3= "Incorrect";
$count2=$count2-1;
}
if($ans4==$answer4)
{
$res4= "Correct";
$count=$count+1;
}
else if($answer4=="")
{
$res4="Not attempted";
}
else
{
$res4= "Incorrect";
$count2=$count2-1;
}
if($ans5==$answer5)
{
$res5= "Correct";
$count=$count+1;
}
else if($answer5=="")
{
$res5="Not attempted";
}
else
{
$res5= "Incorrect";
$count2=$count2-1;
}
if($ans6==$answer6)
{
$res6= "Correct";
$count=$count+1;
}
else if($answer6=="")
{
$res6="Not attempted";
}
else
{
$res6= "Incorrect";
$count2=$count2-1;
}
if($ans7==$answer7)
{
$res7= "Correct";
$count=$count+1;
}
else if($answer7=="")
{
$res7="Not attempted";
}
else
{
$res7= "Incorrect";
$count2=$count2-1;
}
if($ans8==$answer8)
{
$res8= "Correct";
$count=$count+1;
}
else if($answer8=="")
{
$res8="Not attempted";
}
else
{
$res8= "Incorrect";
$count2=$count2-1;
}
if($ans9==$answer9)
{
$res9= "Correct";
$count=$count+1;
}
else if($answer9=="")
{
$res9="Not attempted";
}
else
{
$res9= "Incorrect";
$count2=$count2-1;
}
if($ans10==$answer10)
{
$res10= "Correct";
$count=$count+1;
}
else if($answer10=="")
{
$res10="Not attempted";
}
else
{
$res10= "Incorrect";
$count2=$count2-1;
}
//INCREASE POINTS IN FOLLOWING STATEMENT ONLY USING 2*$COUNT
$finalpoints=$count+$count2;
$_SESSION["pointsession"]= $finalpoints;
Use arrays to store the data:
$count=0;
$count2=0;
$ans = array($answer1,$answer2,$answer3,...);
$answer = array($ans1,$ans2,$ans3,...);
for($i=0;$i<10;$i++){
if($ans[$i]==$answer[$i])
{
$res[$i]= "Correct";
$count=$count+1;
}
else if($answer[$i]=="")
{
$res[$i]="Not attempted";
}
else
{
$res[$i]= "Incorrect";
$count--;
}
}
//INCREASE POINTS IN FOLLOWING STATEMENT ONLY USING 2*$COUNT
$finalpoints=$count+$count2;
$_SESSION["pointsession"]= $finalpoints;
You could do something like this using arrays
$count=0;
$count2=0;
var ans = [$ans1, $ans2.... ];
var answer = [$answer1, $answer2.... ];
var res = [];
answer.forEach(function($answer, i) {
if(ans[i]==$answer)
{
res.push("Correct");
$count=$count+1;
}
else if($answer=="")
{
res.push("Not attempted");
}
else
{
res.push("Incorrect");
$count2=$count2-1;
}
});
$res1 = res[0];
$res2 = res[1];
...
Note that the ... indicate code that you have to fill in
Again, assuming that both questions and answers are in arrays
$count=0;
$ans=array(1,2,3,4,23,1,100);
$answer=array(1,2,'',4,'',54,100);
function mark($answer,$correct){
if( $answer==$correct ) $rv=array('response'=>'correct','score'=>1, 'correct'=>$correct, 'answer'=>$answer );
elseif( $answer=='' ) $rv=array('response'=>'not attempted','score'=>0, 'correct'=>$correct, 'answer'=>$answer );
else $rv=array('response'=>'incorrect','score'=>-1, 'correct'=>$correct, 'answer'=>$answer );
return (object)$rv;
}
for( $i=0; $i < count( $ans ); $i++ ){
$result=mark( $answer[$i], $ans[$i] );
$count += $result->score;
echo 'Question '.( $i+1 ).': Correct answer:' . $result->correct.' Your answer:'.$result->answer.' - '.$result->response . ' - score:'.$result->score.'<br />';
}
echo 'Final score: '.$count.' / '.count($answer);

mt_rand() returns unexpected output

I am working with my ad system of my site and having trouble with this.
<?php
function bdads($size, $company) {
if($company == 'nufa') {
if ($size == '300'){
echo 'n300';
}
if ($size == '160'){
echo 'n160';
}
if ($size == '728'){
echo 'n728';
}
if ($size == '700'){
echo 'n700';
}
}
if($company == 'gnr') {
if ($size == '300'){
echo 'g300';
}
if ($size == '160'){
echo 'g160';
}
if ($size == '728'){
echo 'g728';
}
if ($size == '700'){
echo 'g700';
}
}
}
function bdad($size, $company){
$zsize = $size;
if($company == 'nufa'){
echo bdads($zsize, 'nufa');
}
if($company == 'gnr'){
echo bdads($zsize, 'gnr');
}
if($company == 'both'){
$RandomList = [ bdads($zsize, 'gnr'), bdads($zsize, 'nufa')];
echo $RandomList[mt_rand(0, count($RandomList) - 1)];
}
}
?>
Now, Everything seems fine.. as example,
<?php echo bdad(728, 'gnr'); ?>
returning g728 (as expected)
<?php echo bdad(300, 'nufa'); ?>
returning n300 (as expected)
But all trouble is in generating random content.
<?php echo bdad(300, 'both'); ?>
returning g300n300
I want it to choose either g300 or n300 randomly.
EDIT:
Changed $a to $RandomList, but still same result
I tried to simplify your functions a bit:
You have to return your values, otherwise your functions will return NULL by default. Also you can access a string like an array, so I used $company[0] to get the first letter of the company, which you then can concatenate with the size.
<?php
function bdads($size, $company) {
return $company[0] . $size;
}
function bdad($size, $company){
if($company == "both") {
$RandomList = [bdads($size, "gnr"), bdads($size, "nufa")];
return $RandomList[mt_rand(0, count($RandomList) - 1)];
} else {
return dads($size, $company);
}
}
echo bdad(300, "both");
?>
output:
n300 //Or g300

how to sort SQL result in an existing sorting function

Hello I have this sorting function ine one template of CMS. I would like to add if the condition is the second one:
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
I want to add the following MySQL result to show also
$result = mysql_query("SELECT niches.name, niches.record_num FROM niches ORDER BY name ASC");
which is used in this template for sorting:
include($basepath.'/templates/template.channel_item_title.php');
Any ideas how this can be integrated inside the first code function?
So here is the code of the main index template:
<?
session_start();
if(($_REQUEST[mode] == 'favorites' || $_REQUEST[mode] == 'my_uploads') && !$_SESSION[username]) {
header("Location: /login.php");
}
include('admin/db.php');
include($basepath.'/includes/inc.seo.php');
$cacheName = $_SERVER[REQUEST_URI];
$cacheResult = getCache($cacheName);
$cacheTotalPages = getCache("total_pages$cacheName");
if($cacheResult && $cacheTotalPages) {
$array = $cacheResult;
$total_pages = $cacheTotalPages;
}
else {
include($basepath.'/includes/inc.index_queries.php');
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
if($thispage != 'favorites' && $_GET[mode] != 'my_uploads') {
setCache($cacheName,$array,$overall_cache_time);
setCache("total_pages$cacheName",$total_pages,$overall_cache_time);
}
}
$thisfile = 'index';
$webpage="index";
if($isMobile) {
include($basepath.'/templates/mobile.overall_header.php');
}
else {
include($basepath.'/templates/template.overall_header.php');
}
if(empty($_GET[mode]) && !$_GET[page]) {
include($basepath.'/templates/template.home.php');
}
if($webpage=="index" && empty($_GET[mode]) && !$_GET[page])
{}
else
{
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
}
else {
if($isMobile) {
include($basepath.'/templates/mobile.content_item.php');
}
else
{
include($basepath.'/templates/template.content_item.php');
}
}
}
}
else {
echo "Sorry, no results were found.";
}
}
if($isMobile) {
include($basepath.'/templates/mobile.overall_footer.php');
}
else {
include($basepath.'/templates/template.overall_footer.php');
}
?>
I don't think I get your question, but we have to start somewhere...
<?php
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
Next block of code:
<?php
$result = mysql_query("SELECT niches.name, niches.record_num FROM niches ORDER BY name ASC");
if(is_array(result)) {
foreach($result as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.channel_item_title.php');
}

PHP echo text if variable is blank

I am trying to echo €00.00 if my variable $amount equals zero
I have done something wrong can you help??
Code
while ($row9 = mysql_fetch_array($result9))
{
$amount = $row9['amount'];
}
//$amount = $amount / 60;
//$amount = round($amount, 2);
if $amount == 0 echo "<b>Balance: €00.00</b>";
else
echo "<b>Balance: $$amount</b>";
You need to put the if/else in the loop, and you have some invalid syntax (missing parens and double $). So:
while ($row9 = mysql_fetch_array($result9))
{
$amount = $row9['amount'];
if ($amount == 0)
{
echo "<b>Balance: €00.00</b>";
}
else
{
echo "<b>Balance: $amount</b>";
}
}
You are adding extra $ to the $amount, try this:
if ($amount == 0) {
echo "<b>Balance: €00.00</b>";
} else {
echo "<b>Balance: $amount</b>";
}
In fact you can make your code a bit more readable/standard like this:
if ($amount == 0)
{
echo "<b>Balance: €00.00</b>";
}
else
{
echo "<b>Balance: $amount</b>";
}
I've moved the if statement inside the while loop, cleaned up the code and removed the extra $ sign that was on the last line.
while ($row9 = mysql_fetch_array($result9)) {
if ($row9['amount']) == 0 {
echo "<b>Balance: €00.00</b>";
} else {
echo "<b>Balance: $row9['amount']</b>";
}
}

Categories