Question about a php switch - php

Given the array below, can I do this for the switch(use the variable $cost inside the switch)?
Or does the switch($need a different variable here)
$cost=array(chocoru =>1, oeenergy =>0.35, lemondew =>0.55, chcmyst =>0.25, drsalty =>0.75);
Notice the $cost variable inside the switch is the same as the $cost associative array.
switch($cost)
{
case 1:
echo "You chose lemondew <br />";
echo "the price is".$cost["lemondew"]'<br>';
}

No, you have to iterate over the array with a loop.
foreach($cost as $product => $price)
{
echo "You chose " . $product . "<br />";
echo "the price is" . $price . '<br>';
}

You have a variable called $cost, which is an associative array mapping product names to their price. You can use the product name as array index, there is no need for any other variable or a switch statement:
echo "You chose $product <br />n";
echo "the price is " . $cost[$product] . "<br />n";

It won't work. Variable in switch needs must be equal to any of case values for associated code to be executed.

A switch statement is a lot like a set of ifs. For example:
switch ($var) {
case 1:
$other_var = 6;
break;
case 2:
$other_var = 3;
break;
case 3:
$other_var = 2;
break;
default:
$other_var = 0;
break;
}
is logically equivalent to:
if ($var == 1) {
$other_var = 6;
}
else if ($var == 2) {
$other_var = 3;
}
else if ($var == 3) {
$other_var = 2;
}
else {
$other_var = 0;
}
You want to use a different construct based on what you're trying to do.

No, you must use precise variable, that is one giving exactly one result in evaluation, it might be $cost['chocoru']. But in this case it makes no sense, so best way is, I guess, switching it by name, like:
echo "You chose $name <br />";
echo "the price is".$cost[$name].'<br>';

Related

Change order of output based on if condition

I've build my nice page in PHP, but I would like to get a different output order based on the result of a if condition applied at the beginning of the page.
IE:
if(condition is true){
block n1
block n2 }
else{
block n2
block n1 }
Can you kindly advise on what's the best practices in this case?
I think a flag should solve the problem, but I'm struggling to understand how.
You could prepare you blocks and then exactly what you wrote :
$block1 = "12345";
$block2 = "67890";
$inverted = true;
if ($inverted===true) {
echo $block2.$block1;
} else {
echo $block1.$block2;
}
There are several approaches to this. One would be with if and else and if you have many possibilities, then switch case would be advisable.
$check = 1;
if( $check === 1) {
echo `show 1`;
} else {
echo 'It is not 1';
}
// OR
switch($check) {
case 1:
echo 'Show 1';
break;
case 2:
echo 'Show 2';
break;
case 3:
echo 'Show 3';
break;
default:
echo 'It is not 1,2,3';
}
u can use array just like that
$orders = ['a', 'b'];
if (1 === 1) {
$orders = ['b', 'a'];
}
with this you don't need "else" part
foreach ($orders as $order){
echo $order."<br/>";
}

php if and elseif statements with multiple/more than 3 conditions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to assign random profile pictures to users when they register on a website. I have a problem with my code. If I limit the "if and elseif" statements to 2 conditions, it works well. But when I go over 2 (in this case I have 10 conditions), the code doesn't work. If "switch" statement should be used instead, how would you write the code?
Here is my code
$rand = rand(1,10); //random number between 1 and 10
if($rand == 1)
$profile_pic = "/defaults/profile_pic1.png";
else if($rand == 2)
$profile_pic = "/defaults/profile_pic2.png";
.
.
.
else if($rand == 9)
$profile_pic = "/defaults/profile_pic9.png";
else
$profile_pic = "/defaults/profile_pic10.png";
I hope that's what you want
<?php
$rand = rand(1,10);
switch ($rand) {
case "1":
$profile_pic = "/defaults/profile_pic1.png";
echo "1";
break;
case "2":
$profile_pic = "/defaults/profile_pic2.png";
echo "2";
break;
case "3":
$profile_pic = "/defaults/profile_pic3.png";
echo "3";
break;
case "4":
$profile_pic = "/defaults/profile_pic4.png";
echo "4";
break;
case "5":
$profile_pic = "/defaults/profile_pic5.png";
echo "5";
break;
case "6":
$profile_pic = "/defaults/profile_pic6.png";
echo "6";
break;
case "7":
$profile_pic = "/defaults/profile_pic7.png";
echo "7";
break;
case "8":
$profile_pic = "/defaults/profile_pic8.png";
echo "8";
break;
case "9":
$profile_pic = "/defaults/profile_pic9.png";
echo "9";
break;
case "10":
$profile_pic = "/defaults/profile_pic10.png";
echo "10";
break;
default:
$profile_pic = "/defaults/profile_picDEFAULT.png";
echo "default PHOTO";
}
?>
I really do not understand why you would want to use a switch statement here. In terms of improving the code - you could go with only 2 lines. With if and switch it's 2-3 lines per condition and it's the worst programming practice you might come up with. Just give me a good reason why.
If you read PHP documentation thoroughly, there is the String Operators page available, which explains how your problem might be solved:
concatenation operator (.), which returns the concatenation of its right and left arguments.
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
So you could simply do it with
$rand = rand(1,10);
$profile_pic = "/defaults/profile_pic" . $rand . ".png";
Or you might stumble upon Variable parsing, which states:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
$juice = "apple";
echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
So what you could do is:
$rand = rand(1,10);
$profile_pic = "/defaults/profile_pic${rand}.png";
If you are using the same random number in image path then no need for if or switch loop.
You can use below code.
$rand = rand(1,10) ;
$profile_pic = "/defaults/profile_pic$rand.png";
If you have mapping of random number and images then store it in array and access it.
$rand_image = array(1=>"firstimg.png", 2=>"2.png") ;
$profile_pic = "/defaults/profile_pic".$rand_image[$rand];
<?php
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
?>

PHP case switch statement with variable set in drop-down

HI can someone tell me where I'm going wrong with this code. For some reason the variable $BlogType; isn't going through the Switch statement. This variable is set using a HTML drop-down and I have tested that its value changes accordingly with the user choice using the echo statement at the beginning of the code.
But It doesn't seem to be going past the first 'break;' in the statement, as the echo statement in the Switch code below isn't printed:
echo "<br /> value in case " . $BlogType;
echo "<br /> Blog " . $BlogType; // OK, value changes with dropdown choice
function getParameter($param, $defaultValue) {
if (array_key_exists($param, $_GET)) {
$value=$_GET[$param];
return isSet($value)?$value:$defaultValue;
}
return $defaultValue;
}
$BlogType = getParameter("blog_type", "defaultValue");
$byDate = getParameter("by_date", "defaultValue");
$loopArr = array();
switch ($BlogType) {
case 0:
$loopArr = $all_posts;
break;
case 1:
$loopArr = $music_matters->posts;
echo "<br /> value in case " . $BlogType;
break;
case 2:
$loopArr = $staff_student_news->posts;
break;
case 3:
$loopArr = $kbs_news_events->posts;
break;
default:
$loopArr = array();
}
?>
<?php foreach ($loopArr as $post): {
{ // code here

SWITCH returns TRUE when comparing letters to numbers. WHY?

Short question: WHY?!?
The below class returns ALL ALLRIGHT when calling:Status::validate('ab')
class Status
{
const FRESH = 0;
const PENDING = 25;
const CANCELLED = 50;
public static function validate($status)
{
switch ($status) {
case self::FRESH:
case self::PENDING:
case self::CANCELLED:
echo 'ALL ALLRIGHT';
default:
echo 'ERROR!';
}
die;
}
}
I believe it's because your $status is being casted to int.
$value = 'abc';
$other_value = '21abc';
echo (int)$value;
echo '<br>';
echo (int)$other_value;
Will return:
0
21
And that would cause it to think that ab value is equal to Status::FRESH
I'm not sure though if switch statement does this type of typecasting.
Edit
And I think I was right. More info here PHP Manual - switch.
Reference on typecasting strings to integers here PHP Manual - Strings.
break the case
switch($condition){
case "options": blah(); break;
}

Using conditional values from an array in an if...statement

I have an array of conditions :
$arrConditions = array ('>=2', '==1', '<=10');
...which I want to be able to use in an if...statement.
IE.
if (5 $arrConditions[0])
{
...do something
}
...which would be the same as :
if (5 >= 2)
{
...do something
}
Any help?
Thanks
Such a requirement is a sure sign of a bad design.
Most likely you can do that another, more usual way.
Nevertheless, never use eval for such things.
At least store each operator in pairs - an operator and operand.
$arrConditions = array (
array('>=',2),
array('==',1),
array('<=',10),
);
and then use switch:
list ($operator,$operand) = $arrConditions[0];
switch($operator) {
case '==':
$result = ($input == $operand);
break;
case '>=':
$result = ($input >= $operand);
break;
// and so on
}
But again - most likely you can solve it another, much easier way.
What about this ?
<?php
$arrConditions = array('==2', '==9', '==5', '==1', '==10', '==6', '==7');
$count = 0;
$myval = 0;
foreach ($arrConditions as $cond) {
$str = "if(5 $cond) { return $count;}";
$evalval = eval($str);
if (!empty($evalval)) {
$myval = $count;
}
$count++;
}
switch ($myval) {
case 0: echo '==2 satisfied';
break;
case 1: echo '==9 satisfied';
break;
case 2: echo '==5 satisfied';
break;
case 3: echo '==1 satisfied';
break;
case 4: echo '==10 satisfied';
break;
default : echo 'No condition satisfied';
}
?>

Categories