php switch between range of numbers does not work - php

I have this PHP function for changing color between 2 numbers:
function color_switch($number){
switch (true){
case $number == range(1 , 3):
$color = "progress-bar-danger";
break;
case $number == range(3 , 5):
$color = "progress-bar-warning";
break;
case $number == range(5 , 6):
$color = "progress-bar-default";
break;
case $number == range(6 , 8):
$color = "progress-bar-success";
break;
case $number == range(8, 10):
$color = "progress-bar-success";
break;
}
return $color;
}
But in action this function does not work for me. How should I fix this ?

You are comparing range() which is an array, and $number is integer, which is invalid,
Change your function something like,
function color_switch($number) {
switch ($number) { // switching the function argument
case $number <= 3 : // if less than three, execute case
$color = "progress-bar-danger";
break;
case $number <= 5 :
$color = "progress-bar-warning";
break;
case $number <= 6 :
$color = "progress-bar-default";
break;
case $number <= 8 :
$color = "progress-bar-success";
break;
case $number <= 10 :
$color = "progress-bar-success";
break;
}
return $color;
}

Your utilization of switch is incorrect and your utilization of range() is too.
Your parameter of switch should be the variable you evaluate.
Range() will return an array containing the range.
So the correct code is better :
function color_switch($number) {
switch ($number){
case in_array($number, range(1 , 3)):
$color = "progress-bar-danger";
break;
case in_array($number, range(3 , 5)):
$color = "progress-bar-warning";
break;
case in_array($number, range(5 , 6)):
$color = "progress-bar-default";
break;
case in_array($number, range(6 , 8)):
$color = "progress-bar-success";
break;
case in_array($number, range(8 , 10)):
$color = "progress-bar-success";
break;
}
return $color;
}

Related

How to lower cyclomatic complexity of switch with 11 cases

I have to check if a value is withing a range (0..9, 10..19..up to 100) and return a value depending on the range. The cyclomatic complexity of my function is 12 and I need to lower it to at least 9.
I'm really at a loss here.
I wanted to use an associative array (to use like a Dictionary or a Hash table), but I don't think it works with ranges and I don't want to have an array explicitly declared with 100 entries!
$value = 23;
switch(true) {
case in_array($value, range(0,9)):
return -10;
break;
case in_array($value, range(10,19)):
return -7;
break;
case in_array($value, range(20,29)):
return -5;
break;
case in_array($value, range(30,39)):
return 3;
break;
case in_array($value, range(40,49)):
return 4;
break;
case in_array($value, range(50,59)):
return 5;
break;
case in_array($value, range(60,69)):
return 6;
break;
case in_array($value, range(70,79)):
return 7;
break;
case in_array($value, range(80,89)):
return 8;
break;
case in_array($value, range(90,99)):
return 9;
break;
case in_array($value, range(100,100)):
return 10;
break;
default:
return 0;
break;
}
Can someone help? Is there a simpler way to do that?
TIA
Since the steps are regulary each 10, you can perform an integer division by 10 and lookup the corresponding values in an array:
function theFunc(int $i)
{
return ($i<0 || $i>100) ? 0 : [-10, -7, -5, 3, 4, 5, 6, 7, 8, 9, 10][(int)($i/10)];
}
for($i = -1 ; $i <= 101 ; $i++)
var_dump([$i, theFunc($i)]);
You can just use integer division if the number is greater than 30. You also don't need break; if you are returning, as it will already stop code execution.
switch(true) {
case in_array($value, range(0,9)):
return -10;
case in_array($value, range(10,19)):
return -7;
case in_array($value, range(20,29)):
return -5;
case in_array($value, range(30,100)):
return intdiv($value, 10);
default:
return 0;
}

How to use switch in php

if (isset($_POST["submit"])){
$oride='';
$count = "25";
$origin = $_POST["origin"];
$destinataion = $_POST["destination"];
$oride = ($destination = $_POST["destination"] - $origin= $_POST["origin"]);
switch (true) {
case ($count<="0"):
echo "invalid";
break;
case ($count==="15"):
echo $count;
break;
case ($count==="16"):
$total = $count + "1";
echo $total;
break;
default:
echo "hello";
} }
The code will compute 1st then execute switch depending on what is the result of the computation. I tried if else but it will be too long because the case will go up to 130.
You must use the var $count in switch statement and the constant in case this way
switch ($count) {
case "0" :
echo "invalid";
break;
case "15":
echo $count;
break;
case "16":
$total = $count + "1";
echo $total;
break;
default:
echo "hello";
break;
}
You have to provide an expression to the switch statement, while the case statements are just "versions" of the result of that expression. The only thing you can NOT do directly is the "<= 0" expression, but you can work around it:
if (isset($_POST["submit"])){
$oride='';
$count = "25";
$origin = $_POST["origin"];
$destinataion = $_POST["destination"];
$oride = ($destination = $_POST["destination"] - $origin= $_POST["origin"]);
// --- normalize $count:
$count = $count <= 0 ? 0 : $count;
// use $count as expression:
switch ($count) {
case 0:
echo "invalid";
break;
case "15":
echo $count;
break;
case "16":
$total = $count + "1";
echo $total;
break;
default:
echo "hello";
} }

how to change to english number to nepali number in php

In my project I have to change the english numerals to nepali one upto 2 digits. e.g. if i enter 1 it should return १ and if i enter 41 it should return ४१ and i have to store ४१ in db and show it in front end. How am i to do this? I tried to use "font-family: Preeti;" when getting nepali numerals but it gives ४ and not १. Similarly when I use below function it gives ४ instead of १. How am i to solve this?
function convertNos($nos){
switch($nos){
case"०":return 0;
case"१":return 1;
case"२":return 2;
case"३":return 3;
case"४":return 4;
case"५":return 5;
case"६":return 6;
case"७":return 7;
case"८":return 8;
case"९":return 9;
case"0":return"०";
case"1":return"१";
case"2":return"२";
case"3":return"३";
case"4":return"४";
case"5":return"५";
case"6":return"६";
case"7":return"७";
case"8":return"८";
case"9":return"९";
}
}
Any help/suggestion is welcome.thanks in advance.
/* Set internal character encoding to UTF-8 */
header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding("UTF-8");
// An array of Nepali number representations
function convertNos($nos){
$n = '';
switch($nos){
case "०": $n = 0; break;
case "१": $n = 1; break;
case "२": $n= 2; break;
case "३": $n = 3; break;
case "४": $n = 4; break;
case "५": $n = 5; break;
case "६": $n = 6; break;
case "७": $n = 7; break;
case "८": $n = 8; break;
case "९": $n = 9; break;
case "0": $n = "०"; break;
case "1": $n = "१"; break;
case "2": $n = "२"; break;
case "3": $n = "३"; break;
case "4": $n = "४"; break;
case "5": $n = "५"; break;
case "6": $n = "६"; break;
case "7": $n = "७"; break;
case "8": $n = "८"; break;
case "9": $n = "९"; break;
}
return $n;
}
$num = 0; // get your number
// replace this with whatever you're using to get your number
if (isset($_GET['number'])) $num = strip_tags($_GET['number']);
/* Convert your number (could be a string of unicode,
* not necessarily a digit) into a string and split it
* to get an array of characters.
*/
$str_num = preg_split('//u', ("". $num), -1); // not explode('', ("". $num))
// For each item in your exploded string, retrieve the Nepali equivalent or vice versa.
$out = '';
$out_arr = array_map('convertNos', $str_num);
$out = implode('', $out_arr);
print($out);
// Also make sure your PHP file is saved as a UTF-8 text file
Try utf-8 encoding.
html: <meta charset="utf-8" />
php: header('Content-Type: text/html; charset=utf-8');

My PHP code is not working properly

I´m trying to do some program which would transfer hexa do binary. Problem is in changing of A,B,C,..,F to 10,11,12,...,15 so i can work with them as with numbers. I made this function:
function odstran_pismena($pole)
{
$dlzka = count($pole);
for ($i = 0; $i< $dlzka; $i++)
switch ($pole[$i])
{
case 0: break;
case 1: break;
case 2: break;
case 3: break;
case 4: break;
case 5: break;
case 6: break;
case 7: break;
case 8: break;
case 9: break;
case ("A" || "a"): $pole[$i] = 10;
break;
case ("B" || "b"): $pole[$i] = 11;
break;
case ("C" || "c"): $pole[$i] = 12;
break;
case ("D" || "d"): $pole[$i] = 13;
break;
case ("E" || "e"): $pole[$i] = 14;
break;
case ("F" || "f"): $pole[$i] = 15;
break;
default: $pole[$i] = "ERROR";
break;
}
return $pole;
}
First i made array from string, and now i want to change letters to numbers.
I´m testing it with this string: $test = "AbCdEf2345";
I was expecting result 10 11 12 13 14 15 2 3 4 5 but all i have is 10 10 10 10 10 10 2 3 4 5
Am I doing some mystake?(Of course I am, but where?)
("A" || "a") evaluates to boolean value 'true', so all a to f will get caught by the case ("A" || "a" ) and result in 10.
Without using the hexdec() and with minimal change to your code:
function odstran_pismena($pole)
{
$dlzka = count($pole);
for ($i = 0; $i< $dlzka; $i++)
switch ($pole[$i])
{
case 0: break;
case 1: break;
case 2: break;
case 3: break;
case 4: break;
case 5: break;
case 6: break;
case 7: break;
case 8: break;
case 9: break;
case "A":
case "a": $pole[$i] = 10;
break;
case "B":
case "b": $pole[$i] = 11;
break;
case "C":
case "c": $pole[$i] = 12;
break;
case "D":
case "d": $pole[$i] = 13;
break;
case "E":
case "e": $pole[$i] = 14;
break;
case "F":
case "f": $pole[$i] = 15;
break;
default: $pole[$i] = "ERROR";
break;
}
return $pole;
}
When you have specified case ("A" || "a"): $pole[$i] = 10; it evaluates to true. So all your chars matched against true returns true. for 'case' conditions avoid using expressions. Use the static values your comparing such as
case "A":
case "a":
$pole[$i] = 10;
break;
An easy way to help you with that would be to use a strtolower:
switch(strtolower($pole[$i])) {
case "a" :...
break;
case "b": ...
break;
}
or simply, as the first line of your function:
$pole = strtolower($pole);
This way you won't have to bother with upper/lower casing.
You should use hexdec() and replace you whole for loop with:
for ($i = 0; $i< $dlzka; $i++)
{
$pole[$i] = hexdec($pole[$i]);
}
Note that you will receive a 0 for non-valid values so you might have to check for that separately if it can happen, using for example is_numeric on the original value.

PHP switch case more than one value in the case

I have a variable that holds the values 'Weekly', 'Monthly', 'Quarterly', and 'Annual', and I have another variable that holds the values from 1 to 10.
switch ($var2) {
case 1:
$var3 = 'Weekly';
break;
case 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4:
$var3 = 'Quarterly';
break;
case 5:
$var3 = 'Quarterly';
break;
// etc.
}
It isn't beautiful, because my code has a lot of duplicates. What I want:
switch ($var2) {
case 1, 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4, 5:
$var3 = 'Quarterly';
break;
}
How can I do it in PHP?
The simplest and probably the best way performance-wise would be:
switch ($var2) {
case 1:
case 2:
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case 4:
case 5:
$var3 = 'Quarterly';
break;
}
Also, possible for more complex situations:
switch ($var2) {
case ($var2 == 1 || $var2 == 2):
$var3 = 'Weekly';
break;
case 3:
$var3 = 'Monthly';
break;
case ($var2 == 4 || $var2 == 5):
$var3 = 'Quarterly';
break;
}
In this scenario, $var2 must be set and can not be null or 0
switch ($var2) {
case 1 :
case 2 :
$var3 = 'Weekly';
break;
case 3 :
$var3 = 'Monthly';
break;
case 4 :
case 5 :
$var3 = 'Quarterly';
break;
}
Everything after the first matching case will be executed until a break statement is found. So it just falls through to the next case, which allows you to "group" cases.
If You're reading this and the year is 2021 and beyond, You're also using PHP > 8.0, you can now use the new match expression for this.
this could be
$var3 = match($var2){
1, 2 => 'Weekly',
3 => 'Monthly',
4, 5 => 'Quarterly',
default => 'Annually',
};
Please note that match does identity checks, this is the same as === compared to switch equality check which is ==.
read more about match expression here
Switch is also very handy for A/B testing. Here is the code for randomly testing four different versions of something:
$abctest = mt_rand(1, 1000);
switch ($abctest) {
case ($abctest < 250):
echo "A code here";
break;
case ($abctest < 500):
echo "B code here";
break;
case ($abctest < 750):
echo "C code here";
break;
default:
echo "D code here";
break;
You could use array to store you match groups; like:
<?php
$names = array('Ian', 'Jack', 'Fred', 'Ismail');
$name = 'Vladimir';
switch ($name) {
case (in_array($name, $names)):
echo '<p> Welcome ' . $name . '</p>';
break;
default:
echo '<p>' . $name . ' is a stranger to me?</p>';
}
?>
function bankRemark()
{
$this->db->select('id,status,funding_dt,date,remarks1');
$this->db->from($this->db_sdip);
$this->db->where("amc_remark != '' ");
$query = $this->db->get();
// echo $this->db->last_query();die;
if($query->num_rows() > 0)
{
$data = $query->result();
foreach($data as $val)
{
$id = $val->id;
$status = strtoupper($val->status);
$funding_dt = $val->funding_dt;
$date = $val->date;
$remarks1 = $val->remarks1;
switch ($favcolor) {
case "REFUND":
case "STALE":
if(date("d-m-Y",strtotime($funding_dt)) >= date("d-m-Y",strtotime('31-01-2007')))
{
$this->db->where('id', $id);
$this->db->update($this->db_sdip, array(
'remarks1 ' => 'Rejected',
'amc_remark' => 'Check in FD'
));
}
if( (date("d-m-Y",strtotime($funding_dt)) >= date("d-m-Y",strtotime('01-05-2003'))) and (date("d-m-Y",strtotime($funding_dt)) <= date("d-m-Y",strtotime('31-01-2007'))))
{
if($remarks1 = '')
{
$this->db->where('id', $id);
$this->db->update($this->db_sdip, array(
'remarks1 ' => 'Approved',
'amc_remark' => 'Office Note Dated '.date('d-m-Y')
));
}else{
$this->db->where('id', $id);
$this->db->update($this->db_sdip, array(
'remarks1 ' => 'Rejected',
'amc_remark' => 'Wrong Funding Date'
));
}
}
break;
default:
echo "Invalid Input";
}
}
}
else
{
return NULL;
}
}

Categories