How to simplify if conditions? - php

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

Related

Auto Description From Tags

I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}
I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.

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;

"foreach" causes my function to misbehave

I'm trying to make the following work:
<?php
$item1 = A;
$item2 = B;
$item3 = C;
$array = array($item1, $item2, $item3);
function myFunction () {
if ($item = "A") {
echo "Alpha ";
}
elseif ($item = "B") {
echo "Bravo ";
}
elseif ($item = "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ();
}
?>
The intended effect is that for each item, if the value is A, echo "Alpha", B echo "Bravo" and C echo "Charlie".
However, the output is as follows:
Alpha Alpha Alpha
There were no errors in the error log, so I'm guessing I must have made some kind of mistake not pertaining to syntax. I added an echo $item; before myFunction, and the output is as follows:
AAlpha BAlpha CAlpha
Which means that the $item has been correctly assigned A, B and C. Why doesn't myFunction work like intended?
Thanks in advance!
1) The = is the assignment operator and may not be used for comparisons. Try == or === instead.
2) You assigned $item1 = A but compared $item = "A". However A and "A" are usually different.
3) You didn't pass $item to the function.
In the first if statement you assign "A" to $item and then print out "Alpha" “if "A"”.
Your code should probably look something like this:
<?php
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction ($item) {
if ($item == "A") {
echo "Alpha ";
}
elseif ($item == "B") {
echo "Bravo ";
}
elseif ($item == "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ($item);
}
?>
Set $item parametar on your function.
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction($item){
if($item == "A"){
echo 'Alpha'.'<br/>';
}
elseif ($item == "B") {
echo 'Bravo'.'<br/>';
}
elseif ($item == "C") {
echo 'Charlie'.'<br/>';
}
}
foreach ($array as $item) {
myFunction($item);
}
Also, are you going to pass the variable to your function or what? Otherwise, as it is right now, it should only output "error."
Your function does not have an argument.
foreach ($array as $item) {
myFunction ();
}
How about passing the $item so that your function can actually work:
function myFunction($item) {
and therefore:
foreach($array as $item) {
myFunction($item);
}
<?php
$item1 = "A";
$item2 = "B";
$item3 = "C";
$array = array($item1, $item2, $item3);
function myFunction ($item) {
if ($item == "A") {
echo "Alpha ";
}
elseif ($item == "B") {
echo "Bravo ";
}
elseif ($item == "C") {
echo "Charlie ";
}
else {
echo "Error";
}
}
foreach ($array as $item) {
myFunction ($item);
}
?>

Variable variables created within a for loop

I'd like to change this:
if ($week_day == "1")
{
$day1_hours = $value;
}
if ($week_day == "2")
{
$day2_hours = $value;
}
if ($week_day == "3")
{
$day3_hours = $value;
}
if ($week_day == "4")
{
$day4_hours = $value;
}
if ($week_day == "5")
{
$day5_hours = $value;
}
if ($week_day == "6")
{
$day6_hours = $value;
}
if ($week_day == "7")
{
$day7_hours = $value;
}
}
Into something more readable, like a for loop, or whatever other suggestions you all may have.
I tried to do:
for ($c=1; $c<8, $c++)
{
if ($week_day == $c)
{
$day".$c."_hours = $value;
}
}
But I know that is nowhere near correct, and I have no idea how to insert another variable within a variable.
Any help is appreciated!
Try this syntax.
${'day'.$c.'_hours'} = $value;
Try this
$hours[$week_day] = $value
Something like this
$week_day = 3;
$value = "hi";
${"day" . $week_day . "_hours"} = $value;
echo $day3_hours;
My interpretation.
$week = 7;
$day = array();
for($i=1; $i<=7; $i++){
$day[$i]['hours'] = $value;
}
You can declare the numbers of weeks you want and to pull the data you can do something like this:
echo $day[1]['hours']

Shorter code with For

Is there any way to make this code shorter ?
If ($Item_1 != "_") { $items1 = explode("_", $Item_1); } Else {}
If ($Item_2 != "_") { $items2 = explode("_", $Item_2); } Else {}
If ($Item_3 != "_") { $items3 = explode("_", $Item_3); } Else {}
If ($Item_4 != "_") { $items4 = explode("_", $Item_4); } Else {}
If ($Item_5 != "_") { $items5 = explode("_", $Item_5); } Else {}
If ($Item_6 != "_") { $items6 = explode("_", $Item_6); } Else {}
If ($Item_7 != "_") { $items7 = explode("_", $Item_7); } Else {}
If ($Item_8 != "_") { $items8 = explode("_", $Item_8); } Else {}
If ($Item_9 != "_") { $items9 = explode("_", $Item_9); } Else {}
If ($Item_10 != "_") { $items10 = explode("_", $Item_10); } Else {}
If ($Item_11 != "_") { $items11 = explode("_", $Item_11); } Else {}
If ($Item_12 != "_") { $items12 = explode("_", $Item_12); } Else {}
I try it make shorter with For but it doesnt work example:
For ($i = 1; $i <= 12; $i++) {
If (${$Item_ . $i} != "_") .... dont work for me :/
}
Any ideas?
The idea is good. You just had a little error while building the variable name. Use the following code:
for ($i = 1; $i <= 12; $i++) {
if (${"Item_$i"} != "_") .... should work
}
What you are doing is called variable variables in php. Check the manual about that for further info and examples.
Another idea: Why not using an array? this should suite better here:
$item = array (
'foo', 'bar', 'test', 'xyz', ...
);
for ($i = 1; $i <= count($item); $i++) {
if ($item[$i] != "_")
}
Further note, that you can use the ternary operator to shorten the if statement. (note that I wouldn't do that in this situation because it is less readable, but I'll at least mention it for completeness):
$item[$i] != "_" ? $other[$i] = 'something' : 1; // no else block, just a `NOP 1`;
For clarity try this:
$item_var = "Item_".$i;
If ($$item_var != "_"){}
You should probably be using arrays instead if var1, var2, etc. You could easily use a loop too.

Categories