Create variables from loop - php

I want to be able to create variables with a loop going up to 299. For example, I have the variable $var1 and want to be able to add from there example: $var2 - $var3 - $var4 etc.
for ( $x = 1; $x<=299; $x++ )
{
$var1 = substr($size, 0, 1);
if ($var1 == '1') { $c1 = 'COLOR1'; }
elseif ($var1 == '2') { $var1 = 'COLOR2'; }
elseif ($var1 == '3') { $var1 = 'COLOR3'; };
}
This has been bugging me for sometime.

use arrays in a better way:
for ( $x = 1; $x<=299; $x++ ) {
$var[$x] = substr($size, 0, 1);
switch($var[$x]) {
case "1": $var[$x] = 'COLOR1'; break;
case "2": $var[$x] = 'COLOR2'; break;
case "3": $var[$x] = 'COLOR3'; break;
}
// or the more simple if you follow the same rule
// $var[$x] = "COLOR".$var[$x];
}

Related

How do I query incomplete input

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

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

Adding conditions dynamically in php if condtion

I am trying to add a condition dynamically in the if condition . But it is not working . Please help me to fix the issue.
I am trying a code like this
$day_difference = "some integer value";
if(sheduled_time == 'evening'){
$condition = '>';
}else{
$condition = '==';
}
then
if($day_difference.$condition. 0){
echo "something";
}else{
echo "h";
}
An alternative to gerald's solution; I would suggest that you use a function that validates the inputs using a switch-case operation:
function evaluate ($var1, $operator, $var2)
{
switch $operator
{
case: '<': return ($var1 < $var2);
case: '>': return ($var1 > $var2);
case: '==': return ($var1 == $var2);
}
return null;
}
What you need is the eval() method.
I.e.
$var1 = 11;
$var2 = 110;
$cond1 = '$var1 > $var2';
$cond2 = '$var1 < $var2';
if(eval("return $cond1;")){
echo $cond1;
}
if(eval("return $cond2;")){
echo $cond2;
}
As justly noted beneath, you should exercise the necessary precautions when using this method!
This is not the way to do this.
Just define a function which returns true if the desired conditions are met.
For example, we can define the function decide which receives two arguments, $day_difference and $scheduled_time:
function decide($day_difference, $scheduled_time)
{
if($scheduled_time == 'evening')
{
return $day_difference > 0;
}
else
{
return $day_difference == 0;
}
}
And use it like so:
if( decide($day_difference, $scheduled_time) )
{
echo "something";
}
else
{
echo "h";
}
according to your requirements this can be done using the PHP eval() function which i don't recommend using it only when necessary.
you can check When is eval evil in php?
you can use the below script instead:
if( $sheduled_time == 'evening' && $diff > 0 )
{
echo "This is the Evening and the Difference is Positive";
}
else if($diff == 0)
{
echo "This is not evening";
}
Thankyou for helping me solve my question
I solved this in another way
$day_difference = "some integer value";
$var1 = false ;
if($sheduled_time == 'evening_before'){
if($day_difference > 0 ){
$var1 = true ;
}
}else{
if($day_difference == 0 ){
$var1 = true ;
}
}
if($var1 === true){
echo "something";
}else{
echo "h";
}

What is the best way to do this?

I don't want to repeat the same statements over and over again.
What is the best way to do this?
<?php
if ($a = '3'){
statement 1;
statement 2;
statement 3;
}else if ($a = '2'){
statement 1;
statement 2;
}else if ($a = '1'){
statement 1;
}
?>
To avoid repetitions, you can code:
<?php
($a == '3' or $a == '2' or $a == '1') and statement 1;
($a == '3' or $a == '2' ) and statement 2;
($a == '3' ) and statement 3;
?>
Or, that is the same:
<?php
if ($a == '3' or $a == '2' or $a == '1') { statement 1 ; }
if ($a == '3' or $a == '2' ) { statement 2; }
if ($a == '3' ) { statement 3; }
?>
Also, take a look to Switch statement
Quoting php doc:
The following two examples are two different ways to write the same
thing, one using a series of if and elseif statements, and the other
using the switch statement:
<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>
For your code:
<?php
switch ($a) {
case '3':
statement 1;
statement 2;
statement 3;
break;
case '2':
statement 1;
statement 2;
break;
case '3':
statement 1;
break;
}
?>
<?php
for ($i = 1; $i <= $a; $i++) {
echo $statement . $i;
}
As danihp mentioned, you can use switch. Here's another way without breaks. The downfall of this approach is that you need to create a case for every possible value for $a.
<?php
switch ($a) {
case '3':
statement 3;
case '2':
statement 2;
case '1':
statement 1;
break;
default:
break;
}

php switch case statement to handle ranges

I'm parsing some text and calculating the weight based on some rules. All the characters have the same weight. This would make the switch statement really long can I use ranges in the case statement.
I saw one of the answers advocating associative arrays.
$weights = array(
[a-z][A-Z] => 10,
[0-9] => 100,
['+','-','/','*'] => 250
);
//there are more rules which have been left out for the sake of clarity and brevity
$total_weight = 0;
foreach ($text as $character)
{
$total_weight += $weight[$character];
}
echo $weight;
What is the best way to achieve something like this?
Is there something similar to the bash case statement in php?
Surely writing down each individual character in either the associative array or the switch statement can't be the most elegant solution or is it the only alternative?
Well, you can have ranges in switch statement like:
//just an example, though
$t = "2000";
switch (true) {
case ($t < "1000"):
alert("t is less than 1000");
break
case ($t < "1801"):
alert("t is less than 1801");
break
default:
alert("t is greater than 1800")
}
//OR
switch(true) {
case in_array($t, range(0,20)): //the range from range of 0-20
echo "1";
break;
case in_array($t, range(21,40)): //range of 21-40
echo "2";
break;
}
$str = 'This is a test 123 + 3';
$patterns = array (
'/[a-zA-Z]/' => 10,
'/[0-9]/' => 100,
'/[\+\-\/\*]/' => 250
);
$weight_total = 0;
foreach ($patterns as $pattern => $weight)
{
$weight_total += $weight * preg_match_all ($pattern, $str, $match);;
}
echo $weight_total;
*UPDATE: with default value *
foreach ($patterns as $pattern => $weight)
{
$match_found = preg_match_all ($pattern, $str, $match);
if ($match_found)
{
$weight_total += $weight * $match_found;
}
else
{
$weight_total += 5; // weight by default
}
}
You can specify the character range using regular expression. This saves from writing a really long switch case list. For example,
function find_weight($ch, $arr) {
foreach ($arr as $pat => $weight) {
if (preg_match($pat, $ch)) {
return $weight;
}
}
return 0;
}
$weights = array(
'/[a-zA-Z]/' => 10,
'/[0-9]/' => 100,
'/[+\\-\\/*]/' => 250
);
//there are more rules which have been left out for the sake of clarity and brevity
$total_weight = 0;
$text = 'a1-';
foreach (str_split($text) as $character)
{
$total_weight += find_weight($character, $weights);
}
echo $total_weight; //360
Much different ways to do this.
$var = 0;
$range_const = range(10,20);
switch ($var) {
case 1: $do = 5; break; # 1
case 2: $do = 10; break; # 2
case 3:
case 4:
case 5: $do = 15; break; # 3, 4, 5
default:
if ($var > 5 && $var < 10) { # High performance (6..9)
$do = 20;
} else if (in_array($var, $range_const, true)) { # Looks clear (10..20)
$do = 25;
} else { # NOT in range 1..20
$do = -1;
}
}
print($do);
There no direct range X..Y compares because $var checks to true in each step, but this allows do some nice cheating like this...
$in = create_function('$a,$l,$h', 'return $a>=$l && $a<=$h;');
$var = 4;
switch (true) {
case ($var === 1): echo 1; break;
case ($var === 2): echo 2; break;
case $in($var, 3, 5): echo "3..5"; break;
case $in($var, 6, 10): echo "6..10"; break;
default: echo "else";
}
If you have a more complex conditions, you can wrap them inside a function. Here's an oversimplified example:
$chartID = 20;
$somethingElse = true;
switch (switchRanges($chartID, $somethingElse)) {
case "do this":
echo "This is done";
break;
case "do that":
echo "that is done";
break;
default:
echo "do something different";
}
function switchRanges($chartID, $somethingElse = false)
{
if (in_array($chartID, [20, 30]) && $somethingElse === true) {
return "do this";
}
if (in_array($chartID, [20, 50]) && $somethingElse === false) {
return "do that";
}
}
I think I would do it in a simple way.
switch($t = 100){
case ($t > 99 && $t < 101):
doSomething();
break;
}

Categories