Optimistict way of programming rather than using if else [closed] - php

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
Whats is the best way of optimistic programming in the cases of multiple if else. Heard that usage of multiple if else decreases the programming performance.???

If you have to take decision on the basic single value in this case switch case is very economic in comparison with if, else. suppose we have a variable $data can have various type of value then in this case use of switch case is very economic
switch($data){
case 'username':
// do the thing with username;
break;
case 'anotherdata':
// do the thing with another data;
break;
// do the same
default:
//do default thong
}
if you want to use switch on different variable then you can also use
switch(true) {
case isset($_GET['search']):
include_once 'template/template.search.php';
break;
// do more
default:
//do your work
break;
}
Hope it will help you....

Well if you have several IF statements or ELSEIF statements... you can use a 'SWITCH' instead of IF and ELSEIF. see below.
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}elseif ($i == 3) {
echo "i equals 3";
}
below is the replacment with switch :
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
case 3:
echo "i equals 3";
break;
}
The advantage of the above example is that if any one statement is satisfied the others will not run. They will break and the code will not continue to check the other conditions.
In the above example if $i == 0 the first statement will print and the rest wont be executed.

Related

php switch not functioning as intended

I am attempting to use the switch function of PHP but I must be doing something wrong. The code below will echo the result of the $find_top_type in the console but doesnt seem to go any further. I know the query is good having tested that and verified it through the ECHO. It doesnt seem to go further into the PHP however. It does not show me either of the other ECHO requests.
What am I doing wrong?
$find_top_type = $wpdb->get_var($wpdb->prepare("SELECT column_1 FROM mytable WHERE id = $tid"));
echo $find_top_type;
$find_top_type = 2;
$find_top_type = 4;
$find_top_type = 6;
$find_top_type = 8;
switch($find_top_type){
case 2:
echo "retuning two test";
break;
case "4":
echo "retuning four test";
}
I think you should add default statement and end of switch case and your case 4 have not break statement.

How to use break in if (Command) [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 6 years ago.
Improve this question
I am using $i string for limit in foreach loop.
$i = 0;
foreach($string as $menu){
$i++;
if($i == 6){
break;
}
$menu_name = $menu['name'];
$menu_style = $menu['style'];
// i want to show total 5 menu names.
if($menu_style == 'magazine'){
// i have 5+ menus names (magazine style)
// butt here i want to show just one last magazine
echo $menu_name;
}
if($menu_style == 'normal'){
// i have 5+ names menus (normal style)
// butt here i want to show 4 last normal style
echo $menu_name.'<br>';
}
}
I can't want to use LIMIT in SQL query.
And tell me when i use if($i == 5){ break; } then code display just 4
menu name
Tell me how is display menu name as my required.
Something like that?
$i = 0;
foreach($string as $menu){
$i++;
if($i == 6){
break;
}
$menu_name = $menu['name'];
$menu_style = $menu['style'];
// i want to show total 5 menu names.
if($menu_style == 'magazine' && $i <= 5){
// i have 5+ menus names (magazine style)
// butt here i want to show just one last magazine
echo $menu_name;
} else if($menu_style == 'normal' && $i <= 4){
// i have 5+ names menus (normal style)
// butt here i want to show 4 last normal style
echo $menu_name.'<br>';
}
}

PHP returning value of 1 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
i still cannot get this review system to work properly.
i know the average rating is 3.57 but as soon as i add the if() all i am getting is an output of 1?
// collect 5 lastest reviews for viewing
$sql = "SELECT AVG(rating) FROM reviews WHERE review_id = '$id'";
$query = mysqli_query($conn, $sql);
$AvgReview = mysqli_fetch_row($query);
// Here we have the toatal row count
$AvgReviews = $AvgReview[0];
if($AvgReviews = 1){
echo '1star';
}
//next else is new
else if($AvgReviews >= 1){
echo '2star';
}
//next else is new
else if($AvgReviews >= 2){
echo '3star';
}
//next else is new
else if($AvgReviews >= 3){
echo '4star';
}
//next else is new
else if($AvgReviews >= 4){
echo '5star';
}
You are getting '1star' because you are assigning a value of 1 to $AvgReviews.
Change your code to compare the value.
if ($AvgReviews == 1) {
Additionally, you need to reverse your code or you will end up getting 1 or 2 stars, only.
I would recommend to change it like that:
if ($AvgReviews > 4) {
echo '5star';
}
else if($AvgReviews > 3) {
echo '4star';
}
else if($AvgReviews > 2) {
echo '3star';
}
else if($AvgReviews > 1) {
echo '2star';
}
else {
echo '1star';
}
It's because you're assigning 1 to $AvgReviews. The assignment operator (=) takes the value on the right-hand side, assigns it to the name on the left-hand side, and then returns the value that was assigned. In this case, that's always 1, which PHP interprets as true.
Use the comparison operator instead:
if($AvgReviews == 1){
echo '1star';
}

PHP switch with unknown cases

In a website based on an integer value I need to show text messages to the user. If the website has an integer value that has been not defined in my code, the site breaks.
How can I handle this situation?
My code looks like this:
$status = 1;
switch (status)
{
case 1:
status_from_file();
break;
case 2:
// ...
}
Maybe you are looking for 'default':
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
you should check first if its defined and numeric so -
if(isset($status) && is_numeric($status)){
switch($status){
//cases here
}
}else{
//status is not defined/NaN
}
if its not defined / not a number it will go to "else" block

php: looping thru results from mysql query to increment counter (associative array)

I'm retrieving data from a MySQL db and creating reports from it. I need to get counts when certain conditions are met, and since db queries are rather expensive (and I will have a lot of traffic), I'm looping thru the results from a single query in order to increment a counter.
It seems like it's working (the counter is incrementing) and the results are somewhat close, but the counters are not correct.
At the moment, there are 411 records in the table, but I'm getting numbers like 934 from a ['total'] counter and 927 for ['males'], and that definitely can't be right. However, I get 4 from ['females'], which is correct…
I'm pretty sure it was working last night, but now it's not—I'm quite baffled. (there are still just 411 records)
$surveydata = mysql_query("SELECT `age`,`e_part`,`gender` FROM $db_surveydata;") or die(mysql_error());
$rowcount = mysql_num_rows($surveydata);
$age=array('18+'=>0,'<18'=>0,'total'=>0);
$e_part=array('yes'=>0,'no'=>0,'total'=>0);
$genders=array('male'=>0,'female'=>0,'trans'=>0,'don\'t know'=>0,'total'=>0);
while ($responses = mysql_fetch_assoc($surveydata)) {
foreach ($responses as $response){
switch ($response){
case $responses['age']:
if ($responses['age'] > 18) {$age['18+']++;$age['total']++;}
// i tried putting the ['total'] incrementer in the if/else
// just in case, but same result
else {$age['<18']++;$age['total']++;}
break;
case $responses['e_part']:
if ($responses['e_part']) {$e_part['yes']++;}
else {$e_part['no']++;}
$e_part['total']++;
break;
case $responses['gender']:
switch ($responses['gender']){
case 1:$genders['male']++;break;
case 2:$genders['female']++;break;
case 3:$genders['trans']++;break;
case 9:$genders['don\'t know']++;break;
default:break;
}
$genders['total']++;
break;
default:break;
} // end switch
} //end for
} // end while
thanks!
this is the problem:
foreach ($responses as $response){
switch ($response){
case $responses['age']:
switch $responses looks for match
foreach ($responses as $k=>$v){
switch ($k){
case 'age':
if ($v > 18) ....
mysql_fetch_assoc() retrieves a single row from the table. You then loop over that row, processing each individual field. Then the long set of if() checks to determine which field you're on. That entire structure could be changed to:
while($response = mysql_fetch_assoc($surveydata)) {
if ($responses['age'] > 18) {
$age['18+']++;
} else {
$age['<18']++;
$age['total']++;}
if ($responses['e_part']) {
$e_part['yes']++;
} else {
$e_part['no']++;
}
$e_part['total']++;
switch ($responses['gender']){
case 1:$genders['male']++;break;
case 2:$genders['female']++;break;
case 3:$genders['trans']++;break;
case 9:$genders['don\'t know']++;break;
default:break;
}
$genders['total']++;
}
There's no need for the switch ($response); you can't really switch on an array like that. And even if you could, the 'values' you get wouldn't make any sense -- i'm thinking if it works at all, the value you're switching on would be either 'Array' or the length of the array. (I forget how PHP handles arrays-as-scalars.)
You'll want something like this...
$total = 0;
while ($response = mysql_fetch_assoc($surveydata))
{
if (isset($response['age']))
{
++$age[($response['age'] < 18) ? '<18' : '18+'];
++$age['total'];
}
if (isset($response['e_part']))
{
++$e_part[($responses['e_part']) ? 'yes' : 'no'];
++$e_part['total'];
}
if (isset($response['gender']))
{
switch ($response['gender'])
{
case 1: ++$genders['male']; break;
case 2: ++$genders['female']; break;
case 3: ++$genders['trans']; break;
case 9: ++$genders["don't know"]; break;
}
++$genders['total'];
}
++$total;
}
The benefit of the if (isset(...)) is that if 'age', 'e_part', or 'gender' is null, the corresponding code to count it won't get activated. It does about the same thing as your code, minus the embarrassing loop -- and minus the counting of the field even though it is null, because every row will have the same fields.

Categories