this function only adds numbers and I can not figure why? - php

this function only adds numbers and I can not figure why ?
function calculate($num1 , $num2 , $name = "+" )
{
switch ($name)
{
case "+" || "add" || "a";
return $num1 + $num2 ."<br>";
break;
case "-" || "subtract" || "s";
return $num1 - $num2 ."<br>";
break;
case "*" || "multiply" || "m";
return $num1 * $num2 ."<br>";
break;
default:
"";
}
}
I also tried if statement and didnt work.

Your syntax is not correct, do as follows:
switch ($name) {
case "+" :
case "add" :
case "a":
return $num1 + $num2 . "<br>";
case "-" :
case "subtract" :
case "s":
return $num1 - $num2 . "<br>";
case "*" :
case "multiply" :
case "m":
return $num1 * $num2 . "<br>";
default:
"";
}
By the way, you don't need to break if you return something.
More information :
Switch case multiple values
Switch Documentation

Related

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

php switch between range of numbers does not work

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

Arithmetic operations between variables

I'm beginner with php. I am trying to apply some random arithmetic operation between two variables
$operators = array(
"+",
"-",
"*",
"/"
);
$num1 = 10;
$num2 = 5;
$result = $num1 . $operators[array_rand($operators)] . $num2;
echo $result;
it prints values like these
10+5
10-5
How can I edit my code in order to do this arithmetic operation?
While you could use eval() to do this, it relies on the variables being safe.
This is much, much safer:
function compute($num1, $operator, $num2) {
switch($operator) {
case "+": return $num1 + $num2;
case "-": return $num1 - $num2;
case "*": return $num1 * $num2;
case "/": return $num1 / $num2;
// you can define more operators here, and they don't
// have to keep to PHP syntax. For instance:
case "^": return pow($num1, $num2);
// and handle errors:
default: throw new UnexpectedValueException("Invalid operator");
}
}
Now you can call:
echo compute($num1, $operators[array_rand($operators)], $num2);
This should work for you!
You can use this function:
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = preg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
//As an example
echo calculate_string("10+5");
Output:
15
So in your case you can do this:
$operators = array(
"+",
"-",
"*",
"/"
);
$num1 = 10;
$num2 = 5;
echo calculate_string($num1 . $operators[array_rand($operators)] . $num2);

Echoing out a usable operator in PHP [duplicate]

This question already has answers here:
Execute PHP code in a string [duplicate]
(3 answers)
Closed 8 years ago.
Say I had this code below:
$operator = "+";
$num1 = 10;
$num2 = 32;
echo "the sum of " . $num1 . " and " . $num2 . " is " . ($num1.$operator.$num2);
As you can see, I'm trying to use a variable to define the operator by concatenating it. However, when running this code, the operator is displayed as plain text instead of being used to answer the question.
Obviously, I get an output like this: "the sum of 10 and 32 is 10+32"
Surely I'm doing something wrong?
Avoid eval as much as possible. But here is the answer to do it with eval:
<?php
$operator = '+';
$num1 = 10;
$num2 = 32;
eval(sprintf('echo %d %s %d;', $num1, $operator, $num2));
Here a little cleaner code
$operator = '+';
$num1 = 10;
$num2 = 32;
switch ($operator) {
case '+':
$result = $num1 + $num2;
break;
case '-':
$result = $num1 - $num2;
break;
case '*':
$result = $num1 * $num2;
break;
case '/':
$result = $num1 / $num2;
break;
default:
echo "Invalid operator";
break;
}
echo 'Result: ' . $result;

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