If-else statement in just one line for simple text [duplicate] - php

This question already has answers here:
if block inside echo statement?
(4 answers)
Closed 11 months ago.
I want to write some text Year: X | percentage: $percentage%, where X is based on the value contained in $year.
$year can be 2010, 2011... but also 0. In this case, we have to write the word "All"; otherwise, the year itself.
Year: 2011 | percentage: 2% // case $year not 0
Year: All | percentage: 2% // case $year == 0
This code seems very long for what is required:
echo "year: ";
if ($year==0)
echo "All";
else
echo $year;
echo " | Percentage: $percentage%";
So I wonder: how can we make this code shorter and clearer?
Note I posted my own answer because I wanted to share the way I found after spending some time working on it. Anyway, I see there are other ones that look quite good.

You can use a ternary operator:
echo ( condition ? "if condition true" : "otherwise")
For this specific case:
echo "Year: ". ((0==$year) ? "All" : $year) ." | Percentage: $percentage%";

Might not be a direct answer to you questions, but IMHO you should do something like:
$renderedYear = $year;
if ($year == 0) {
$renderedYear = 'All';
}
echo 'Year: ' . $renderedYear . ' | Percentage: ' . $percentage . '%';
Always prefer readability over shortness of code. Pixels on screen are waaaay cheaper than debugging time.
Also instead of concatenating you may want to use *printf.

I am sorry if this doesnt work (cant test it right now) but in C (which is somewhat similar to php) you can negate numbers directly, i belive you could also use:
echo "Year: ". (!$year ? "All" : $year) ." | Percentage: $percentage%";

I would style it using sprintf() as it's far easier to read.
echo sprintf("year: %s | Percentage: %s %%", ($year == 0) ? "All" : $year, $percentage);

Related

Does Using Same Declared Variable Name To Make Calculations Make Sense? [duplicate]

This question already has answers here:
Better way to add number to itself?
(9 answers)
Closed 5 years ago.
I'm wondering if this following piece of code makes sense from a PHP perspective:
if(isset($_POST['submit'])){
$year = $_POST['year'];
$month = $_POST['month'];
if($month == 'December'){
$month = 'January';
$year = $year + 1;//can this be done?
}
}
Sure. You could also do:
$year++;
or
$year += 1;
Yes, makes sense and is safe. The right side is evaluated first. There are shortcuts for these operations:
A = A op B
A op= B
So:
$year += 1;
And with everything else as well (-= *= /= .=). For incrementing a single unit, there is also $year++ or $year-- for decrementing, plus the variations ++$year and --$year.
Please check out the manual pages for Assignment Operators and Increment Operators.
Since you're using + operator you're telling php to mathematically sum both values, therefore both of them will be parsed as integer (or float) values before actually making the sum. So if $month's value is "10" (string), it will be parsed as 10 (integer) and then you will have 10 + 1 = 11.

How to use 2 variables in For loop? [duplicate]

This question already has answers here:
Php for loop with 2 variables?
(7 answers)
Closed 6 years ago.
My PHP code (so far not working as I want it to) -
for ($x=0, $y=0; $x<=163, $y<=98 ; $x++, $y++) {
echo "Value of x = " . $x . " & y = " . $y . "<br>";
}
What I was trying to achieve is - it should echo even if one condition matches. Right now it stops when one condition is fulfilled, i.e. in this case when y=98, it stopped. Also there may be cases when y>=x in contrast to given code where x>y
Edit -
The duplicate marked question, did not solve my problem as in that question, range of both the variables were same, so it could have been achieved by the mentioned answer (by increasing one variable). In my case both variables has different range.
Also I tried this
for ($x=0, $y=0; $x<=163 || $y<=98 ; $x++, $y++) {
echo "Value of x = " . $x . " & y = " . $y . "<br>";
}
But it's also not helping me to achieve my desired output.
Edit 2 - I think I couldn't explain properly earlier, with what I wanted the output to be.
So I am trying to demonstrate by small e.g. with x=3, y=2
x=1, y=1
x=2, y=1
x=3, y=1
x=1, y=2
x=2, y=2
x=3, y=2
I am trying to achieve something like this. I don't know, what this ?matrix is called in maths (so it's possible my question title is wrong).
You can achieve that through a basic nested loop. Basically you loop over y in the outer loop and for each iteration of y you do a another for loop for x. Try this and adjust x and y as necessary.
<?php
for ($y=0; $y<=98 ; $y++) {
for ($x=0; $x<=163; $x++) {
echo "Value of x = " . $x . " & y = " . $y . "<br>";
}
}

PHP - Showing different text between different dates (3 Different Text to be shown)

I am new to PHP and i want to show 3 different text during different date periods.
e.g. 01/01 - 01/04 = TERM 1, 20/04 - 01/06 = TERM 2, 01/07 - 31/10 = TERM 3.
Can someone help me with that. I have not been able to write a code for that.
Thanking You In Advance.
Regards
Akshat Gupta
Hello Akshat please find the simplified solution below
<?php
$current_date = date('Y-m-d');
if(strtotime($current_date)>strtotime('2015-01-01') && strtotime($current_date)<strtotime('2015-04-01'))
{
echo "TERM 1";
}
elseif(strtotime($current_date)>strtotime('2015-04-20') && strtotime($current_date)<strtotime('2015-06-01'))
{
echo "TERM 2";
}
elseif(strtotime($current_date)>strtotime('2015-07-01') && strtotime($current_date)<strtotime('2015-10-31'))
{
echo "TERM 3";
}
?>
I have tested it and its working fine
you can do it by some if's...
so i write something can so such thing one year one year...for example from now on till next year it'll show term 1 and next year will show term 2 and go on... hope it helps..
<?php
date_default_timezone_set('UTC');
$date = date('Y/m');
echo $date;
if(date('Y')>="2015" && date('Y')<"2016" && date('m') >="02" && date('m')<"03" )
echo "term1";
if(date('Y')>="2016" && date('Y')<"2017" && date('m') >="02" && date('m')<"03" )
echo "term1";
if(date('Y')>="2017" && date('Y')<"2018" && date('m') >="02" && date('m')<"03" )
echo "term1";
i just echo the $date to show you how to get current system time...
the link below will help...
http://php.net/manual/en/function.date.php

simple grouping with php while loop?

I am outputting a table of rates. Each rate period has a Daily Rate and a Weekly rate, but the rate PERIODS remain the same.
So I am attempting to change the background color after ever TWO sets. So basically, the table will show:
Date 1 - Weekly Rate
Date 1 - Daily Rate
<change bg color>
Date 2 - Weekly Rate
Date 2 - Daily Rate
<change bg color back to original>
At the moment, I have two styles set up for background colors in my stylesheet. And the code i am using is giving me ALTERNATING rows. I just cannot see why it's changing every one, instead of every OTHER one!
To do this, I MUST compare one Date1 to Date2. ( I cannot make it change every two iterations, for reasons I do not want to go into.)
Here is my code so far inside the while loop. Help! And thank you.
if ($previous !== $row[datefrom])
{
$thecolor = "bg1";
}
else
{
$thecolor = "bg2";
}
echo "<tr class=\"".$thecolor."\"> \n";
echo "<td>" . $row[datefrom] . " - " . $row[dateto]. "</td> \n";
echo "<td>" . str_replace(" 3-5","",$row[Ratetype]) . "</td> \n";
echo "<td>$" . $row[Rate] . "</td> \n";
echo "</tr> \n";
$previous = $row[datefrom];
You also have to remember last used background color, without it background will change only for first entry in group. Example:
$use_original_bg = TRUE;
for(/*...*/){
if ($previous !== $row[datefrom]) {
$use_original_bg = !$use_original_bg;
}
$thecolor = $use_original_bg?"bg1":"bg2";
}
We can see the reason for this very easy if we set up the states of current date and prev for each iteration:
1. date1, prev = nothing => bg1
2. date1, prev = date1 => bg2
3. date2, prev = date1 => bg1
4. date2, prev = date2 => bg2
One easy way to solve this problem is to also take into account the state of the background. I'll leave that up to you to give it some thinking.

Changing text depending on rounded total from database

On a website I have a number of small PHP scripts to automate changes to the text of the site, depending on a figure that's calculated from a MySQL database. The site is for a fundraising group, and the text in question on the home page gives the total amount raised.
The amount raised is pulled from the database and rounded to the nearest thousand. This is the PHP I use to round the figure and find the last three digits of the total:
$query4 = mysql_query("SELECT SUM(amountraised) AS full_total FROM fundraisingtotal;");
$result4 = mysql_fetch_array($query4);
$fulltotal = $result4["full_total"];
$num = $fulltotal + 30000;
$ftotalr = round($num,-3);
$roundnum = round($num);
$string = $roundnum;
$length = strlen($string);
$characters = 3;
$start = $length - $characters;
$string = substr($string , $start ,$characters);
$figure = $string;
(£30,000 is the amount that had been raised by the previous fundraising team from when the project first started, which is why I've added 30000 to $fulltotal for the $num variable)
Currently the text reads:
the bookstall and other fundraising events have raised more than £<? echo number_format($ftotalr); ?>
I've just realised though that because the PHP is rounding to the nearest thousand, if the total's for example £39,200 and it's rounded to £40,000, to say it's more than £40,000 is incorrect, and in that case I'd need it to say 'almost £40,000' or something similar. I obviously need to replace the 'more than' with a variable.
Obviously I need to test whether the last three digits of the total are nearer to 0 or 1000, so that if the total was for example £39,2000, the text would read 'just over', if it was between £39,250 and £39,400 something like 'over', between £39,400 and £39,700 something like 'well over', and between £39,700 and £39,999, 'almost.'
I've managed to get the last three digits of the total as a variable, and I think I need some sort of an if/else/elseif code block (not sure if that would be the right approach, or whether to use case/break), and obviously I'm going to have to check whether the figure meets each of the criteria, but I can't figure out how to do that. Could anyone suggest what would be the best way to do this please?
Instead of nested if else blocks, you could have a function that takes in the dollar amount and inside the function throw the variable in a switch case statement and at a particular case return the correct echo'd text.
Switch cases provide readability over several if else statements. If you need coIde examples, let me know.
Update:
Performing comparisons on integers only, switch case is the best bet. When comparing conditions that result in a boolean value, using if else is what you need.
I had took your code and switched the case to be if else and here is what it looks like with an example output:
function qualifier($figure) {
if ($figure < 249) return "just over";
elseif ($figure < 399) return "over";
elseif ($figure < 699) return "well over";
elseif ($figure < 999) return "almost";
else return "No number entered";
}
echo "We are " . qualifier(250) . " our goal!";
// outputs: "We are over our goal!"
The simplest and most elegant solution imho would be, like Lizard pointed out, to floor the value and always say "over". You could even make exception for the first-1000 problem and floor anything below that to the next 100 or so, something like...
<?
function getFlooredText($amount) {
if($amount < 1000) {
return floor($amount/100)*100;
} else {
return floor($amount/1000)*1000;
}
}
echo "We've raised over £" . getFlooredText(455) . "\n"; // 400
echo "We've raised over £" . getFlooredText(1455) . "\n"; // 1000
echo "We've raised over £" . getFlooredText(38800) . "\n"; // 38000
?>
If you absolutely don't want that you could always do a four or five layer if-sandwich, it would be the easiest approach towards the idea you described but maybe not the prettiest. Something like this, if I understood where you were going with it...
<?
function getRoundedText($amount) {
$n = substr($amount, -3);
if($n < 250) {
return "just over £" . round($amount, -3);
} elseif($n < 500) {
return "well over £" . round($amount, -3);
} elseif($n < 750) {
return "close to £" . round($amount, -3);
} elseif($n < 1000) {
return "almost £" . round($amount, -3);
}
}
echo "We've raised " . getRoundedText(38200) . "\n";
echo "We've raised " . getRoundedText(38400) . "\n";
echo "We've raised " . getRoundedText(38700) . "\n";
echo "We've raised " . getRoundedText(38900) . "\n";
?>
Hope that helps.
You might not need to change the text... take a look at the floor function http://php.net/manual/en/function.floor.php
It will always round down, so you can still say 'more than'.
I would use "approximately" to cover all cases!

Categories