How do I query incomplete input - php

I want to transform query string like pending, shipped or cancel to number status.
$q = strtolower($keyword);
if($q == 'pen' or $q == 'pend' or $q == 'pending' ) {
$d = 1;
} elseif($q == 'shi' or $q == 'ship' or $q == 'shipped') {
$d = 2;
} elseif($q == 'can' or $q == 'cancel' ) {
$d = 3;
} else {
$d = 4;
}
$query->whereStatus($d);
Current query working fine but too much or. It's possible to do in shorten way?

str_is(query, stringToSearch) will probably be enough:
if (str_is('pen*', $q)) {
$d = 1;
}
Else you could parse them from arrays:
$pendingArray = ['pen', 'pend', 'pending'];
if (in_array($q, $pendingArray)) {
$d = 1;
}

If these are all the conditions you need, you could always use a switch.
$q = strtolower($keyword);
$d = 4;
switch($q) {
case 'pen':
case 'pend':
case 'pending':
case 'pen':
$d = 1;
break;
case 'shi':
case 'ship':
case 'shipped':
$d = 2;
break;
case 'can':
case 'cancel':
$d = 3;
break;
}
$query->whereStatus($d);
If this needs to be called on a model, it could be saved to a Laravel scope function like so:
on Laravel model
public function scopeSearchStatus($query, $keyword) {
/** All the code above **/
}
Then it can be called cleanly anywhere you'd like:
SomeModel::searchStatus($keyword);

You could also try this:
<?php
$q = strtolower($keyword);
$d = (preg_match('/\b(pen|pend|pending)\b/', $q)) ? 1 : 4;
$d = (preg_match('/\b(shi|ship|shipped)\b/', $q)) ? 2 : 4;
$d = (preg_match('/\b(can|cancel|)\b/', $q)) ? 3 : 4;
$query->whereStatus($d);

Related

Can If Statment created based on loop?

For example
$InitArray[1] = 4;
$InitArray[2] = 5;
$InitArray[3] = 6;
I want to make if statment with that syntax
if($Type = /* key */){
$Position = /* value */
}
which means
if($Type = 1){
$Position = 4;
}
if($Type = 2){
$Position = 5;
}
if($Type = 3){
$Position = 6;
}
How to make that if statment through array loop?
Edit :
Array isn't static , User put his own array
,It Could be like that for example
$InitArray[4] = 34;
$InitArray[5] = 13;
or
$InitArray[6] = 12;
$InitArray[13] = 84;
$InitArray[52] = 23;
$InitArray[78] = 10;
what I mean is something like this
foreach($InitArray as $TypeWritten => $PositionWritten){
if($Type = $TypeWritten){
$Position = $PositionWritten;
}
}
The Equal comparison operator in php is double equal sign ==. So you need to at least change all if statement to use == instead of =.
foreach($InitArray as $TypeWritten => $PositionWritten){
if($Type == $TypeWritten){
$Position = $PositionWritten;
// some code to use the $Position variable ...
// ...
}
}
You're just missing the correct comparison operator. Just change the = into == (or === if the variables you are comparing are of the same type),
foreach($InitArray as $TypeWritten => $PositionWritten){
if($Type == $TypeWritten){
$Position = $PositionWritten;
}
}
Hope this helps,

How to reset variable a,b,c,and score after loop?

i want to count my score from option a/b/c that inputted from a form. for each input given, value from a =1,b=2,c=3 ,after count i want to save the result in score variable
in my controller
public function score($id) {
$user_login = Auth::user()->id;
$answers = Answer::select('user_answer')->where('jenis_quiz_id','=',$id)->where('user_id','=',$user_login)->get();
static $a = 0;
static $b = 0;
static $c = 0;
static $score = 0;
if($answers->count()) {
foreach ($answers as $answer) {
if ($answer->user_answer == '1') {
$a++;
} else if($answer->user_answer == '2') {
$b++;
} elseif($answer->user_answer == '3') {
$c++;
}
}
}
$score = $a+$b+$c;
$returnScore = $score;
$a = null;
$b = null;
$c = null;
$score = null;
return $returnScore;
}
public function getShowResultOfQuiz($id) {
$categoryquiz = JenisQuiz::findOrFail($id);
$user = Auth::user()->id;
$score= $this->score($id);
$kelas = Auth::user()->kelas;
$instansi = Auth::user()->instansi;
History::create([
'user_id'=>$user,
'jenis_quiz_id'=>$id,
'score'=> $score,
'kelas' => $kelas,
'instansi' => $instansi
]);
// $time_taken = date("H:i:s", strtotime(Answer::whereJenisQuizId($id)->orderBy('id', 'desc')->first()->time_taken));
switch ($id) {
case '1':
return view('quiz1',compact('score','categoryquiz'));
case '2':
return view('quiz2',compact('score','categoryquiz'));
case '3':
return view('quiz3',compact('score','categoryquiz'));
}
}
i want to reset a,b,c,and score variables every input submitted,and the problem is score always added from previous submitted answer instead of reset it before calculating the score again, help me , thanks

Nested if conditions doesn't work

I have nested if conditions on my project but i have a problem;
if(isset($_GET['q']) && isset($_GET['t'])) {
$query = $_GET['q'];
$type = $_GET['t'];
$none_key = FALSE;
if($type = 'singer') {
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%'");
$control = $singers->rowCount();
if($control > 0) {
$on_page = 24;
$number_singers = $singers->rowCount();
$number_page = ceil($number_singers/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$singers = $connect->query("SELECT * FROM lyrica_singers WHERE singer_name LIKE '%$query%' ORDER BY singer_name ASC LIMIT ".$limit.",".$on_page);
$singer_key = TRUE;
} else {
$none_key = TRUE;
}
}
if($type = 'song') {
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%'");
$control = $songs->rowCount();
if($control > 0) {
$on_page = 24;
$number_songs = $songs->rowCount();
$number_page = ceil($number_songs/$on_page);
$page = isset($_GET['p']) ? (int) $_GET['p'] : 1;
if ($page < 1) $page = 1;
if ($page>$number_page) $page = $number_page;
$limit = ($page - 1) * $on_page;
$songs = $connect->query("SELECT * FROM lyrica_songs WHERE song_name LIKE '%$query%' ORDER BY song_name ASC LIMIT ".$limit.",".$on_page);
$song_key = TRUE;
} else {
$none_key = TRUE;
}
}
} else {
$key = TRUE;
}
When I run the code, I am expecting that if one of the'control' variables is bigger than 0 the 'none_key' variable must be equal to 0. When the 'type' varible is 'song' there is no problem but if the 'type' variable is 'singer' then 'none_key' variable printing 1, I think it is running the second if block and becomes 'none_key' 1 because of the second 'control' variable is not bigger than zero.
This is an assignment, it sets $type to the value singer:
if ($type = 'singer') {
You want a comparison, it checks to see if $type equals the value singer:
if ($type == 'singer') {
[Edit] Some people prefer to write this sort of statement with the variable last. This is commonly called a "Yoda condition":
if ('singer' == $type) {
This way, if you screw up and only use one =, you get an error.

Working around for loop [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have noticed similar repetition and trying to work around using a single for loop for this if I can to minimize the code length:
I wouldn't need to use a switch case if I can form a loop instead?
$returnNo variable starts at 5, each case multiplied by 2 then minus 1.
where it shows "$a<=", it starts at 5 and each case multiplied by 2 then plus 3.
the if() statement starting at if($matchno == 7), each case multiplied by 2 then plus 1.
the final if() statement starting at if($matchno == 8), each case multiplied by 2.
I have done up to case 64, it will actually go up to 512. As I know the code is repeating I am hoping someone can help me produce a single loop for this?
Many thanks!
switch($max) {
case 80 :
$returnNO = 5;
for($a = 1; $a<=5; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 7){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 8){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 160 :
$returnNO = 9;
for($a = 1; $a<=13; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 15){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 16){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 320 :
$returnNO = 17;
for($a = 1; $a<=29; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 31){
$matchinfo['winner'] = true;
return $matchinfo;
} elseif($matchno == 32){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
case 640 :
$returnNO = 33;
for($a = 1; $a<=61; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == 63){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == 64){
$matchinfo['third_winner'] = true;
return $matchinfo;
}
break;
}
}
I'll use the first two cases as an example:
switch ($max) {
case 80:
$returnNO = 5;
$loopCount = 5;
$winner = 7;
$thirdWinner = 8;
break;
case 160:
$returnNO = 9;
$loopCount = 13;
$winner = 15;
$thirdWinner = 16;
break;
...
}
for ($a = 1; $a <= $loopCount; $a++) {
if ($matchno == $a || $matchno == ($a + 1)) {
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
}
if ($matchno == $winner) {
$matchinfo['winner'] = true;
return $matchinfo;
} else if ($matchno == $thirdWinner) {
$matchinfo['third_winner'] = true;
return $matchinfo;
}
Simply explained, remove the code that repeats all the time and try to parameterize it (either by creating a function or by putting all repeated code somewhere else... in this example, I put the repeating code after the switch statement and paremeterized it.
If I understood well, here is an alternative solution which I think would work for all cases you specified, with no use of switch case.
$div10 = $max / 10;
$maxLoop = $div10 - 3;
$returnNO = $div10 / 2 + 1;
for($a = 1; $a<=$maxLoop; $a++) {
if($matchno == $a || $matchno == ($a+1)){
$matchinfo['matchno'] = $returnNO;
$matchinfo['place'] = ($matchno == $a ? 'clan1' : 'clan2');
return $matchinfo;
}
$returnNO++;
$a++;
}
if($matchno == ($div10-1)){
$matchinfo['winner'] = true;
return $matchinfo;
}elseif($matchno == $div10){
$matchinfo['third_winner'] = true;
return $matchinfo;
}

Returning a default grade from a score value

Here is my problem. I upload a csv file containing two columns (student Number and Score). But when i form an HTML table from the data, i'll like to have a column display a grade according to the score uploaded... Also all the courses that have a score >40 should all be put into another table. Below is the loop i'm trying to make work, but it's not getting me anywhere near it.
Thanks for the help. I most appreciate it. Thanks
while ($row4 = mysql_fetch_assoc($query4)) {
if ($row4['score'] >= 70) {
$grade = A;
}
elseif ($row4['score'] >= 60) {
$grade = B;
}
elseif ($row4['score'] >= 50) {
$grade = C;
}
elseif ($row4['score'] >= 45) {
$grade = D;
}
elseif($row4['score'] >= 40) {
$grade = E;
}
elseif($row4['score'] >= 40) {
$grade = F;
}else {
$grade = AR;
}
}
If I understand correctly, the following should do what you are looking for. I assume that your Course ID and Student ID are in the database row, but you will need to update those if not.
<?php
define('GRADE_A_MIN', 70);
define('GRADE_B_MIN', 60);
define('GRADE_C_MIN', 50);
define('GRADE_D_MIN', 45);
define('GRADE_E_MIN', 40);
define('GRADE_F_MIN', 35);
$table_one_values = array(); // Used to create table for students with scores 40+
$table_two_values = array();
while ($row4 = mysql_fetch_assoc($query4)) {
$score = $row4['score'];
$destination_table = 'two';
if ( $score >= GRADE_A_MIN ) {
$grade = 'A';
$destination_table = 'one';
} elseif ( $score >= GRADE_B_MIN ) {
$grade = 'B';
$destination_table = 'one';
} elseif ( $score >= GRADE_C_MIN ) {
$grade = 'C';
$destination_table = 'one';
} elseif ( $score >= GRADE_D_MIN ) {
$grade = 'D';
$destination_table = 'one';
} elseif ( $score >= GRADE_E_MIN ) {
$grade = 'E';
$destination_table = 'one';
} elseif ( $score >= GRADE_F_MIN ) {
$grade = 'F';
} else {
$grade = 'AR';
}
$table = 'table_'.$destination_table.'_values';
$$table[] = array(
'course_id' => $row4['course_id'],
'student_id' => $row4['student_id'],
'score' => $score,
'grade' => $grade
);
}
Some problems:
Your $grade variable gets overwritten in the loop so you only will have the last value at the end. As your row contains a student number as well, you could do something like: $grade[$row4['number']] = 'A'; to link that specific grade to a specific student number. Note that you would set your array before the loop: $grade = array();
Your assignment is wrong, unless A, B, etc. are constants. It should probably be 'A' instead of A, etc. So: $grade[$row4['number']] = 'C';, etc.

Categories