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

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);

Related

How to Catch variable when data no available

I wan't to make Number of patient registration queue, I have trouble when data registration for today isn't available.
here is my code :
Controllers :
function index()
{
$this->load->helper('url');
$data['tbl_pendaftaran'] = $this->m_pendaftaran->getData()->result();
$data['pasien']=$this->m_pendaftaran->getPasien();
$data['kpendaftaran']=$this->m_pendaftaran->get_no_pendaftaran();
//status
$data['status'] = $this->m_pendaftaran->status()->result();
$this->template->load('template','pendaftaran/v_pendaftaran',$data);
}
Models :
function status()
{
$this->db->select('*');
$this->db->from('tbl_pendaftaran');
$this->db->join('tbl_pasien', 'tbl_pendaftaran.id_pasien = tbl_pasien.id');
$this->db->where('status','menunggu');
$this->db->limit(1);
return $this->db->get();
}
View :
<?php
foreach ($status as $key ) {
}
$cur = date("Y-m-d H:i:s",time());
if ($key->tgl_berobat<$cur) {
echo "No Patient for Today";
} else {
echo $key->no_antrian;
}
?>
here is result of Error when data for today Isn't available :
Severity: Notice
Message: Undefined variable: key
Filename: views/v_pendaftaran.php
Line Number: 22
Look like you have typing mistake here or you wrongly closed the foreach loop:
<?php
foreach ($status as $key ) {
}
$cur = date("Y-m-d H:i:s",time());
if ($key->tgl_berobat<$cur) {
echo "No Patient for Today";
} else {
echo $key->no_antrian;
}
?>
TRY THIS:
<?php
foreach ($status as $key ) {
$cur = date("Y-m-d H:i:s",time());
if ($key->tgl_berobat < $cur) {
echo "No Patient for Today";
} else {
echo $key->no_antrian;
}
}
?>
To respond to your comment try this way:
<?php
if(isset($status) && !empty($status)){
foreach ($status as $key ) {
$cur = date("Y-m-d H:i:s",time());
if ($key->tgl_berobat < $cur) {
echo "No Patient for Today";
} else {
echo $key->no_antrian;
}
}
} else {
echo "No Patient for Today";
}
//OR
if(isset($status) && !empty($status)){
foreach ($status as $key ) {
$cur = date("Y-m-d H:i:s",time());
if(isset($key->tgl_berobat) && !empty($key->tgl_berobat)){
if ($key->tgl_berobat < $cur) {
echo "No Patient for Today";
} else {
echo $key->no_antrian;
}
} else {
echo "No Patient for Today";
}
}
} else {
echo "No Patient for Today";
}
?>
I think the trouble is in your View.
Just change the code to
<?php
foreach ($status as $key ) {
$cur = date("Y-m-d H:i:s",time());
if ($key->tgl_berobat<$cur) {
echo "No Patient for Today";
} else {
echo $key->no_antrian;
}
}
?>
In your controller do not call result function, cause maybe there is no an object to result it.
function index()
{
.
.
.
//status
$data['status'] = $this->m_pendaftaran->status();
$this->template->load('template','pendaftaran/v_pendaftaran',$data);
}
In your check first if object exist or not:
<?php
if($status->num_rows()>0)
{
foreach ($status->result() as $key ) {
$cur = date("Y-m-d H:i:s",time());
if ($key->tgl_berobat<$cur) {
echo "No Patient for Today";
} else {
echo $key->no_antrian;
}
}
}
?>

Several nearly identical if statements need to be shortened

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>";
}
}
}

Better Way of Writing If else statement

Is there any better way of writing this:
if (in_array('WIN_WAITING', $statuses)) {
$this->globalStatus = 'WIN_WAITING';
} else if (in_array('IN_PLAY', $statuses)) {
$this->globalStatus = 'IN_PLAY';
} else if (in_array('WON', $statuses)) {
$this->pay($this->tickets['ticketID']);
$this->globalStatus = 'WON';
} else if (in_array('PAYEDOUT', $statuses)) {
$this->globalStatus = 'PAYEDOUT';
} else if (in_array('CLOSED', $statuses)) {
$this->globalStatus = 'CLOSED';
} else if (in_array('LOST', $statuses)) {
$this->globalStatus = 'LOST';
} else if (in_array('OPEN', $statuses)) {
$this->globalStatus = 'OPEN';
}
This should work for you:
(Here I just loop through all of your search strings and if I found it I break out the loop)
<?php
$search = ["WIN_WAITING", "IN_PLAY", "WON", "PAYEDOUT", "CLOSED", "LOST", "OPEN"];
foreach($search as $v) {
if(in_array($v, $statuses)) {
if($v == "WON") $this->pay($this->tickets['ticketID']);
$this->globalStatus = $v;
break;
}
}
?>
Maybe something like
$options = array('WIN_WAITING', 'IN_PLAY', 'WON', 'PAYEDOUT', 'CLOSED', 'LOST', 'OPEN');
for($i=0; $i<=7; $i++) {
if(in_array($options[$i], $statuses)) {
$this->globalStatus = $options[$i];
break;
}
}
Not tested, just an idea

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');
}

count conditional output in foreach loop

I have foreach loop like this
foreach($destinations as $destination)
{
if($destination=="abc")
{
$msg = "Yes";
}
else
{
$msg = "No";
}
}
How can I count number of "Yes" and "No" generated by "if statement" outside "foreach loop"?
Try:
$yes = 0;
$no = 0;
foreach($destinations as $destination)
{
if($destination=="abc")
{
$yes += 1;
}
else
{
$no += 1;
}
}
echo "Yes " . $yes . "<br>" . "No " . $no;
Inside 'if' statement you can try this
$yesCount = 0;
$noCount = 0;
foreach($destinations as $destination)
{
if($destination=="abc")
{
$yesCount++;
$msg = "Yes";
}
else
{
$noCount++;
$msg = "No";
}
}
But i am not sure whether it can be used outside.
$yesCount = 0;
$noCount = 0;
foreach($destinations as $destination) {
if($destination=="abc") {
$msg = "Yes";
$yesCount = $yesCount + 1;
}
else {
$msg = "No";
$noCount = $noCount + 1;
}
}
echo $yesCoynt . " --- " . $noCount;
Just try with the following example :
<?php
$destinations = array('abc','def','ghi');
foreach($destinations as $destination)
{
if($destination=="abc")
{
$msg = "Yes";
$msg_yes_counter[]= "I'm in";
}
else
{
$msg = "No";
$msg_no_counter[]= "I'm in";
}
}
echo "YES -> My Count is :".count($msg_yes_counter);
echo "NO -> My Count is :".count($msg_no_counter);
?>
Create two flag variables and try this
$yesFlag=0;
$noFlag=0;
foreach($destinations as $destination)
{
if($destination=="abc")
{
$msg = "Yes";
$yesFlag++;
}
else
{
$msg = "No";
$noFlag++;
}
}
echo "no. of Yes:".yesFlag;
echo "no. of NO:".noFlag;
Use the array_count_values() function, no need for a loop at all then.
array_count_values($destinations);

Categories