How to skip to next "elseif" in PHP statement? - php

If you have an if/else statement like the one below, is there a way to check something inside the first matching if and tell it to skip ahead to the next else/if, and do this multiple times?
continue seemed promising after some googling, but didn't work so maybe that's only for loops
if ($teamscore > 100) {
if ($somethingelse=$something) {
//skip to the next "elseif"
}
} elseif ($teamscore > 95) {
if ($somethingelse=$something) {
//skip to the next "elseif"
}
} elseif ($teamscore > 90) {
} else {
}

It seems like what you're going for is sort of like a switch, but you can't evaluate separate expressions in each case, so you can't use it for inequalities like this. I think this structure could be used instead.
while (true) {
if ($teamscore > 100) {
// DO STUFF
if ($somethingelse != $something) {
break;
}
}
if ($teamscore > 95) {
// DO STUFF
if ($somethingelse != $something) {
break;
}
}
if ($teamscore > 90) {
// DO STUFF
if ($somethingelse != $something) {
break;
}
}
break;
}
However, if // DO STUFF is the same thing in each if block, or a variation of the same thing that fits a pattern, you probably could use a loop instead to avoid the repetition.
for ($score = 100; $score > 85; $score -= 5) {
if ($teamscore > $score) {
// DO STUFF
}
if ($somethingelse != $something) {
break;
}
}

You should turn your condition bodies (in my example, the echo's) into functions:
if ($foo == 'bar') {
echo 'it is bar!';
} elseif ($foo == 'foobar') {
echo 'it is is foobar!';
} else {
echo 'it\'s nada!';
}
becomes:
function sayBar()
{
return 'it is bar!';
}
function sayFooBar()
{
return 'it is foobar!';
}
function sayNada()
{
return 'it\'s nada!';
}
if ($foo == 'bar') {
echo sayBar();
if ($bar == 'Treybake is awesome') {
echo sayFooBar();
}
} elseif ($foo == 'foobar') {
echo sayFooBar();
} else {
echo sayNada();
}

you might be looking for somthing like this,
if ($teamscore > 100 && $somethingelse !== $something) {
} elseif ($teamscore > 95 && $somethingelse !== $something) {
} elseif ($teamscore > 90 && $somethingelse !== $something) {
} else {
}

Related

Several nearly identical if statements need to be shortened

So I've got this code...
code:
if(empty($day0[2])) {
echo "<td>".$day0[1]."<br></td>";
} else {
if(strcmp($day0[1],"Absent") == 0) {
echo "<td>".$day0[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day0[1]."<br>Time: ".#$day0[2]." - ".#$day0[3]."</td>";
}
}
if(empty($day1[2])) {
echo "<td>".$day1[1]."<br></td>";
} else {
if(strcmp($day1[1],"Absent") == 0) {
echo "<td>".$day1[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day1[1]."<br>Time: ".#$day1[2]." - ".#$day1[3]."</td>";
}
}
if(empty($day2[2])) {
echo "<td>".$day2[1]."<br></td>";
} else {
if(strcmp($day2[1],"Absent") == 0) {
echo "<td>".$day2[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day2[1]."<br>Time: ".#$day2[2]." - ".#$day2[3]."</td>";
}
}
if(empty($day3[2])) {
echo "<td>".$day3[1]."<br></td>";
} else {
if(strcmp($day3[1],"Absent") == 0) {
echo "<td>".$day3[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day3[1]."<br>Time: ".#$day3[2]." - ".#$day3[3]."</td>";
}
}
if(empty($day4[2])) {
echo "<td>".$day4[1]."<br></td>";
} else {
if(strcmp($day4[1],"Absent") == 0) {
echo "<td>".$day4[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day4[1]."<br>Time: ".#$day4[2]." - ".#$day4[3]."</td>";
}
}
if(empty($day5[2])) {
echo "<td>".$day5[1]."<br></td>";
} else {
if(strcmp($day5[1],"Absent") == 0) {
echo "<td>".$day5[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day5[1]."<br>Time: ".#$day5[2]." - ".#$day5[3]."</td>";
}
}
if(empty($day6[2])) {
echo "<td>".$day6[1]."<br></td>";
} else {
if(strcmp($day6[1],"Absent") == 0) {
echo "<td>".$day6[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day6[1]."<br>Time: ".#$day6[2]." - ".#$day6[3]."</td>";
}
}
Where day 0-6 equals Sunday through Saturday, and the array numbers attached to each one equals a different variable in a multi-dim array.
That is several if statements that are all exactly the same except the variable name inside of each one. I haven't been able to find a way to make this shorter, so I thought I would post here to try and see if anyone has any ideas on how I can combine this into shorter lines of code. I'm all about my code looking neater and functioning better, and I think this could teach a lot of people good ways to shorten their code down a bit.
First merge all array of $day[n] in to $finalArray
foreach($finalArray as $key=>$value){
if(empty($value[2])) {
echo "<td>".$value[1]."<br></td>";
} else {
if(strcmp($value[1],"Absent") == 0) {
echo "<td>".$value[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$value[1]."<br>Time: ".#$value[2]." - ".#$value[3]."</td>";
}
}
}
#MagnusEriksson suggested making a function, I think this is the best way to do it.
From 69 lines of code to 18 lines of code.
function displayTime($day1,$day2,$day3) {
if(empty($day2)) {
return "<td>{$day1}<br></td>";
} else {
if(strcmp($day1,"Absent") == 0) {
return "<td>{$day1}<br>Time: N/A</td>";
}
return "<td>{$day1}<br>Time: {$day2} - {$day3}</td>";
}
}
for ($x = 0; $x <= 6; $x++) {
echo displayTime(${"day$x"}[1],${"day$x"}[2],${"day$x"}[3]);
}
Please try with this code.
$array=array($day0,$day1,$day2,$day3);
for($i=0;$i<count($array);$i++){
if(empty($day.$i[2])) {
echo "<td>".$day.$i[1]."<br></td>";
} else {
if(strcmp($day.$i[1],"Absent") == 0) {
echo "<td>".$day.$i[1]."<br>Time: N/A</td>";
} else {
echo "<td>".$day.$i[1]."<br>Time: ".#$day.$i[2]." - ".#$day.$i[3]."</td>";
}
}
}

Create a loop or array in php for comparing multiple sessions coming from different pages

I have multiple pages and each page has multiple radio buttons which pass values and after checking different selections across all radio buttons output a unique result currently I am creating too many if conditions which is difficult to main, can an array or loop be done for it.
<?php
if(isset($_POST['material'])) {
$_SESSION['material'] = $_POST['material'];
// for screw
if($_SESSION['category'] == "Screw" ) {
if($_SESSION['headtype'] == "Counter Sink Philips") {
if($_SESSION['diameter'] == "6 MM"){
if($_SESSION['length'] == "10 MM"){
if($_SESSION['pitch'] == "1 MM") {
if($_SESSION['material'] == "Brass") {
echo "kenenth start with database";
}
}
}
}
}
}
// for self tapping
if($_SESSION['category'] == "Self Tapping" ) {
if($_SESSION['headtype'] == "Counter Sink Philips") {
if($_SESSION['diameter'] == "6 MM"){
if($_SESSION['length'] == "10 MM"){
if($_SESSION['pitch'] == "1 MM") {
if($_SESSION['material'] == "Brass") {
echo "Self Tapping";
}
}
}
}
}
}
// for stud
if($_SESSION['category'] == "Stud" ) {
if($_SESSION['headtype'] == "Counter Sink Philips") {
if($_SESSION['diameter'] == "6 MM"){
if($_SESSION['length'] == "10 MM"){
if($_SESSION['pitch'] == "1 MM") {
if($_SESSION['material'] == "Brass") {
echo "Stud";
}
}
}
}
}
}
}
?>
You could write a recursive function to do that for you:
function in_array_r($find, $yourArray, $strict = false) {
foreach ($yourArray as $item) {
if (($strict ? $item === $find : $item == $find) || (is_array($item) && in_array_r($find, $item, $strict))) {
return true;
}
}
return false;
}
usage
$a['category'] = array("Screw", "Self Tapping", "Stud");
$a['headtype'] = array("Counter Sink Philips", "Counter Sink Philips"));
echo in_array_r($_SESSION['category'], $a) ? 'found' : 'not found';
This should do it
$dataToCheck["category"] = "multipleoptions";
$dataToCheck["headtype"] = "Counter Sink Philips";
// etc...
$found = true;
$foundWhat = "";
foreach ($dataToCheck as $key => $value)
{
if($key == "category" && ($_SESSION[$key] == "Screw" || $_SESSION[$key] == "Self Tapping" || $_SESSION[$key] == "Stud"))
{
$foundWhat = $_SESSION[$key];
continue;
}
else
{
found = false;
break; // Unknown category
}
if($_SESSION[$key] != $value )
{
$found = false;
break;
}
}
if($found == true)
echo $foundWhat;

PHP checking if all inputs were set doesn't function?

So I started using MVC. I don't use a framework. It's just self-practice.
So this is my register part:
protected function _instance()
{
if ($_POST != null)
{
/**
* Validating if forms are not empty
**/
if (self::validateForms())
{
echo 1;
}
else
{
new Error("One of the forums was empty..");
}
}
}
private static function validateForms()
{
$inputs = array (
'username', 'password', 'repassword',
'email', 'password_f', 'repassword_f',
'display'
);
$i = 0;
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
}
Now it only must check if inputs were set, if not, throw error.
But it seems like it doesn't work as it always runs that error.
$i must grow everytime a input was full, but I don't think it does.
When I do echo $i, it only echoing "1".
Why is it only looping through it once?
The problem is you are returning within your loop after the first test.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
}
}
should be
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}
or more concisely
foreach ($inputs as $key)
{
if (!isset($_POST[$key]) || empty($_POST[$key]))
{
return false;
}
}
return true;
You need to take the checking of $i out of the loop so that it checks how many were actually set once all the inputs have been cycled through. Otherwise, it is checking on the first time, seeing that it is not equal and returning false.
foreach ($inputs as $key)
{
if (isset($_POST[$key]) && !empty($_POST[$key]))
{
$i++;
}
}
if ((int) $i == count($inputs))
{
return true;
}
else
{
return false;
}

how to sort SQL result in an existing sorting function

Hello I have this sorting function ine one template of CMS. I would like to add if the condition is the second one:
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
I want to add the following MySQL result to show also
$result = mysql_query("SELECT niches.name, niches.record_num FROM niches ORDER BY name ASC");
which is used in this template for sorting:
include($basepath.'/templates/template.channel_item_title.php');
Any ideas how this can be integrated inside the first code function?
So here is the code of the main index template:
<?
session_start();
if(($_REQUEST[mode] == 'favorites' || $_REQUEST[mode] == 'my_uploads') && !$_SESSION[username]) {
header("Location: /login.php");
}
include('admin/db.php');
include($basepath.'/includes/inc.seo.php');
$cacheName = $_SERVER[REQUEST_URI];
$cacheResult = getCache($cacheName);
$cacheTotalPages = getCache("total_pages$cacheName");
if($cacheResult && $cacheTotalPages) {
$array = $cacheResult;
$total_pages = $cacheTotalPages;
}
else {
include($basepath.'/includes/inc.index_queries.php');
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
if($thispage != 'favorites' && $_GET[mode] != 'my_uploads') {
setCache($cacheName,$array,$overall_cache_time);
setCache("total_pages$cacheName",$total_pages,$overall_cache_time);
}
}
$thisfile = 'index';
$webpage="index";
if($isMobile) {
include($basepath.'/templates/mobile.overall_header.php');
}
else {
include($basepath.'/templates/template.overall_header.php');
}
if(empty($_GET[mode]) && !$_GET[page]) {
include($basepath.'/templates/template.home.php');
}
if($webpage=="index" && empty($_GET[mode]) && !$_GET[page])
{}
else
{
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
}
else {
if($isMobile) {
include($basepath.'/templates/mobile.content_item.php');
}
else
{
include($basepath.'/templates/template.content_item.php');
}
}
}
}
else {
echo "Sorry, no results were found.";
}
}
if($isMobile) {
include($basepath.'/templates/mobile.overall_footer.php');
}
else {
include($basepath.'/templates/template.overall_footer.php');
}
?>
I don't think I get your question, but we have to start somewhere...
<?php
if(is_array($array)) {
foreach($array as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.content_item_photo.php');
}
Next block of code:
<?php
$result = mysql_query("SELECT niches.name, niches.record_num FROM niches ORDER BY name ASC");
if(is_array(result)) {
foreach($result as $row) {
if($row[photos] == 1) {
if($isMobile) {
include($basepath.'/templates/mobile.content_item_photo.php');
}
else
{
include($basepath.'/templates/template.channel_item_title.php');
}

How to simplify if conditions?

How can I simplify if conditions, because per each condition I make a new if/elseif and its a lot of code, this is what I have:
$chapters = array('1:data1', '2:data2', '4:datax', '3:datag');
sort($chapters);
$screenshots = array('1:screen1', '2:screen2', '3:screen3', '4:go4');
$chapterCount = count($chapters);
$chapterItems = 0;
foreach ($screenshots as $key => $screenshot) {
$screenshotInfo = explode(':', $screenshot);
$screen[$screenshotInfo[0]] = $screenshotInfo[1];
}
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
// If is the first chapter
if ($chapterNumber == 1) {
echo '<li>'.$chapterInfo[0].'</li>';
// If have only one chapter
if ($chapterItems+1 == $chapterCount) {
echo '<li>'.$screen[$chapterNumber].'</li>';
}
}
// If is a new chapter
elseif ($currentNumber != $chapterNumber) {
echo '<li>'.$screen[$chapterNumber-1].'</li>';
echo '<li>'.$chapterInfo[0].'</li>';
// If is new and last chapter
if ($chapterItems+1 == $chapterCount) {
echo '<li>'.$screen[$chapterNumber].'</li>';
}
}
// If is the last chapter
elseif ($chapterItems+1 == $chapterCount) {
echo '<li>'.$chapterInfo[0].'</li>';
echo '<li>'.$screen[$chapterNumber].'</li>';
}
else {
echo '<li>'.$chapterInfo[0].'</li>';
}
$currentNumber = $chapterNumber;
$chapterItems++;
}
That code works perfect on my tests but I'm sure it have a lot of unneeded code.
If brevity is of more interest than readability, you can use ternary statements.
$foo = true;
$bar = $foo ? 'something' : 'nothing';
echo $bar;
//returns 'something'
$foo = false;
$bar = $foo ? 'something' : 'nothing';
$echo bar;
//returns 'nothing'
May be you could use a function for all the if-conditions. Since all the if-conditions inside are same we could use something like:
$chapters = array('1:data1', '2:data2', '4:datax', '3:datag');
sort($chapters);
$screenshots = array('1:screen1', '2:screen2', '3:screen3', '4:go4');
$chapterCount = count($chapters);
$chapterItems = 0;
foreach ($screenshots as $key => $screenshot) {
$screenshotInfo = explode(':', $screenshot);
$screen[$screenshotInfo[0]] = $screenshotInfo[1];
}
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
if ($chapterNumber == 1) { // If is the first chapter
echo '<li>'.$chapterInfo[0].'</li>';
echo compare($chapterItems,$chapterCount,$screen,$chapterNumber); // If have only one chapter
} elseif ($currentNumber != $chapterNumber) { // If is a new chapter
echo '<li>'.$screen[$chapterNumber-1].'</li>';
echo '<li>'.$chapterInfo[0].'</li>';
echo compare($chapterItems,$chapterCount,$screen,$chapterNumber); // If is new and last chapter
} elseif ($chapterItems+1 == $chapterCount) { // If is the last chapter
echo '<li>'.$chapterInfo[0].'</li>';
echo '<li>'.$screen[$chapterNumber].'</li>';
} else {
echo '<li>'.$chapterInfo[0].'</li>';
}
$currentNumber = $chapterNumber;
$chapterItems++;
}
function compare($chapterItems,$chapterCount,$screen,$chapterNumber) {
if ($chapterItems+1 == $chapterCount) {
return '<li>'.$screen[$chapterNumber].'</li>';
}
return false;
}
Hope this helps you :)
If you check the original code you will see that:
echo '<li>'.$chapterInfo[0].'</li>';
will be printed in every scenario. So we don't actually need an if for that.
The only checks you need is:
isNew and not isFirst
if ($currentNumber != $chapterNumber && $chapterNumber != 1)
so we can print the 'new header':
echo '<li>'.$screen[$chapterNumber-1].'</li>';
And if it's the last one, so we can print the last item footer:
echo '<li>'.$screen[$chapterNumber].'</li>';
So we can simplify by having the bellow code:
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
// If is new AND is not the first print the 'New item header'
if ($currentNumber != $chapterNumber && $chapterNumber != 1) {
echo '<li>'.$screen[$chapterNumber-1].'</li>';
}
// This was being printed in every scenario, so we don't need a if for that
echo '<li>'.$chapterInfo[0].'</li>';
// If it is the last, print the 'Last item footer'
if ($chapterItems+1 == $chapterCount) {
echo '<li>'.$screen[$chapterNumber].'</li>';
}
$currentNumber = $chapterNumber;
$chapterItems++;
}
if your goal is just to remove if/else and get easier code coverage you can do the same thing but only with ternaries like that:
foreach ($chapters as $chapter) {
$chapterInfo = explode(':', $chapter);
$chapterNumber = current($chapterInfo);
echo ($currentNumber != $chapterNumber && $chapterNumber != 1) ? sprintf('<li> %s </li>', $screen[$chapterNumber - 1]) : '';
echo sprintf('<li> %s </li>', $chapterInfo[0]);
echo ($chapterItems + 1 == $chapterCount)? sprintf('<li> %s </li>', $screen[$chapterNumber]): '';
$currentNumber = $chapterNumber;
$chapterItems++;
}

Categories