PHP switch statement "echoing" the wrong case - php

$year = readline('Type your year of birth: ');
$age = 2023 - $year;
switch ($age) {
case ($age < 0):
echo 'I don't see in the future.';
break;
case ($age >= 0) && ($age <= 3):
echo 'Congrats. A newborn capable of using the PC.';
break;
case ($age > 3):
echo 'Our system calculated that you are:' . ' ' . $age . ' ' . 'years old';
break;
}
So this is from my first lesson of PHP and the statement "echoes" the first case if I input 2023 but it should echo the second one. Any idea why this happens?

Change the switch ($age) to switch (true).
Try this:
switch (true) {
case ($age < 0):
echo "I don't see in the future.";
break;
case ($age >= 0) && ($age <= 3):
echo "Congrats. A newborn capable of using the PC.";
break;
case ($age > 3):
echo "Our system calculated that you are:" . " " . $age . " " . "years old";
break;
default:
break;
}

cases are values, not expressions to evaluate. It looks like you meant to use an if-else:
if ($age < 0) {
echo 'I don\'t see in the future.';
} elseif ($age >= 0) && ($age <= 3) {
echo 'Congrats. A newborn capable of using the PC.';
} else if ($age > 3) { # Could have also been an "else", without the condition
echo 'Our system calculated that you are:' . ' ' . $age . ' ' . 'years old';
}

Related

Get price according distance

i am trying to create dynamic price calculation by distance.My requirment similar like this
so I need a function where I can pass
distance and then get price by distance
From 0 -10km = Rs10rs/km (fixed price)
10-15km = rs10Rs/km
15 -20km = 9rs pre/km
20 -30km = 8.5rs per/km
25 -30km = 8rs per/km
30 -40km = 7.5rs per/km
30km -50km above = 7rs / km
foreach ($usersInfo as $index=> $users)
{
$km= 0;
$ridefrom=$users['ride_from'];
$rideto=$users['ride_to'];//this is from lat long
$tempLatLong = explode(',',$users['ride_from']);
$tempLatLong1 = explode(',',$users['ride_to']);
$key = array('lat','long');
$to = array_combine($key,$tempLatLong);
$from = array_combine($key,$tempLatLong1);
$km=distanceCalculation($from['lat'],$from['long'],$to['lat'],$to['long']).'km';
$usersInfo[$index]['distance'] =$km;
$carprice=10;// price will be change dynamical from back end admin can change this.
if($carprice){
$price=$km*10;
}
else{
$price=$km*9;
}
$usersInfo[$index]['price'] =$price;
return $usersInfo;
}
Try something like this:
function price_per_km($distance, $mode) {
if ($mode == 'car') {
switch (true) {
case $distance <= 10:
return 10*$distance;
case $distance <= 15:
return 10*$distance;
case $distance <= 20:
return 9*$distance;
case $distance <= 25:
return 8.5*$distance;
case $distance <= 30:
return 8*$distance;
case $distance <= 40:
return 7.5*$distance;
default:
return 7*$distance;
}
}
else {
// bike
switch (true) {
case $distance <= 10:
return 12*$distance;
case $distance <= 15:
return 11*$distance;
case $distance <= 20:
return 10*$distance;
case $distance <= 25:
return 9*$distance;
default:
return 8*$distance;
}
}
}
echo price_per_km(5, 'car') . "\n";
echo price_per_km(12, 'car') . "\n";
echo price_per_km(25, 'car') . "\n";
echo price_per_km(35, 'car') . "\n";
echo price_per_km(5, 'bike') . "\n";
echo price_per_km(15, 'bike') . "\n";
echo price_per_km(35, 'bike') . "\n";
Output:
50
120
212.5
227.5
60
165
270

Why does this block of code result in a blank space?

My goal is to subtract the two times and then generate a logged in checker from there.
What I need to know, is if I have correctly subtracted the two times in minutes.
PHP Version: 7.0
Time is entered into the DB using NOW() and shows as (Example: 2016-07-23 15:01:34)
For some reason, where this code is included in HTML, is just blank.
Code (everything is defined higher up in the code) :
<?php
include ('../includes/connection.php');
include ('../scripts/functions.php');
$getOnlineAdmins = $handler->prepare('SELECT * FROM Admins WHERE AdminLevel >= :al AND Status= :stat');
$statn = 1;
$aln = 1;
$getOnlineAdmins->bindParam(':al', $aln);
$getOnlineAdmins->bindParam(':stat', $statn);
$getOnlineAdmins->execute();
echo "
<table class='table-fill'>
<thead>
<tr>
<th class='text-left' style='padding-left: 12px; padding-right: 12px;';></th>
</tr>
</thead>
<tbody class='table-hover'>";
if ($getOnlineAdmins->rowCount() >=1){
echo ("These is one or more rows.");
while ($results = $getOnlineAdmins->fetch()){
if((strtotime($results['LastVisited']) + 900) >= time()){
echo ("Time requirement met.");
switch ($results['AdminLevel']) {
case 3:
$rank = 'In-Training/Intern';
break;
case 6:
$rank = 'Community Moderator';
break;
case 9:
$rank = 'Senior Moderator';
break;
case 12:
$rank = 'Supervisor';
break;
case 15:
$rank = 'Administrator';
break;
case 18:
$rank = 'Senior Administrator';
break;
case 21:
$rank = 'Staff Advisor';
break;
case 24:
$rank = 'Engineer';
break;
case 27:
$rank = 'Vice Chairman';
break;
case 30:
$rank = 'Chairman';
break;
case 33:
$rank = 'Website Engineer';
break;
default:
$rank = 'Unknown';
break;
}
echo "<tr>";
echo "<td>" . $results['Username'] . " - " . $rank . "</td>";
} else {
echo "<tr><td>{$results['Username']} – $rank</td>";
}
}
}else{
echo "<tr><td>There are no staff members online.</td>";
}
echo " </tbody>
</table>";
?>
As far as I understand it, now() is not getting the current time as you expect it to. See this question for what I believe to be the root of your misunderstanding.
Assuming $results['LastVisited'] is in the format 2016-07-23 14:11:02 – you could convert it to a UNIX timestamp with strtotime.
So if the time 15 minutes ago is less than or equal to your last visited time:
if (strtotime('-15 minutes') <= strtotime($results['LastVisited'])) {}
Alternative format with time() – that you would use instead of the MySQL equivalent UNIX_TIMESTAMP():
if ((time() - 900) <= strtotime($results['LastVisited'])) {}

Verify if a value is included between two numbers

I am working with PHP and I want to verify if a specific number is between 2 numbers and if it returns TRUE then we display a message
if($number is between $value1 and $value2){
echo 'Ok';
}else{
echo 'not Ok';
}
PS: $number can be $value1 or $value2
Try this way
if($number >= $value1 && $number <= $value2){
echo 'Ok';
}else{
echo 'not Ok';
}
Logic :
So basically if a number is greater than a value and lesser than another value, it is considered to be in between the two.
Hope it helps !
function isBetween($number, $value1, $value2) {
return $number >= $value1 && $number <= $value2;
}
. . . .
if(isBetween(1, 0.5, 2.5))
echo "Ok";
else
echo "Not Ok";
Pretty self-explanatory
$number = 10;
$min_value = 5;
$max_value = 15;
// if $min_value <= $number <= $max_value
if( min( max($number, $min_value), $max_value) === $number ) {
// Value is between range
}
Though this might be the slowest solution, it can be useful in some cases. Here is little comparison against other methods.

Echo Out Interger Differently If More Than Value PHP

So I'm creating a points system for my website which I want to change to an echo instead of the actual integer when shown on the users profile.
For example: When the integer is lower than 1000 it displays as the actual number (lets say: 645). But when it is between 1000 and 1100, it will display as '1k' and so on. What I've got so far does work, but displays incorrectly and does seem a bit of a waste of space.. Is there any way to do this in a much simpler; faster way?
Thanks!
code:
<?php
$points_disp = $user_data['points'];
if($points_disp < 1000){
echo $points_disp;
} else if ($points_disp >= 1000){
echo '1k';
} else if ($points_disp >= 1200){
echo '1.2k';
} else if ($points_disp >= 1400){
echo '1.4k';
} else if ($points_disp >= 1600){
echo '1.6k';
} else if ($points_disp >= 1800){
echo '1.8k';
} else if ($points_disp >= 2000){
echo '2k';
}
?>
Edit: I figured out an easier way to do this;
code (for anyone else who needs to do this):
<?php
$points_disp = $user_data['points'];
$fdigit = substr($points_disp, 0, 1);
$sdigit = substr($points_disp, 1, 1);
if ($points_disp < 1000){
echo $points_disp;
} else if ($points_disp >= 1000){
echo $fdigit . "." . $sdigit . "k";
}
echo $num;
?>
You can use switch case:
$points_disp = $user_data['points'];
switch(true)
{
case ($points_disp < 1000):
$num = $points_disp;
break;
case ($points_disp > 1000 && $points_disp < 1100 ):
$num = '1.2k';
break;
//...so on
}
echo $num;
Try this,
if($points_disp < 1000){
echo $points_disp;
} else if($points_disp >= 1000) {
echo round($points_disp/1000,1) . "K";
}

PHP Change background on Time

So, For school i have to make PHP show the time, And for example when it is 12:00 the background is a afternoon one, and on 02:00 it is a Night one. This is my code:
<body>
<?php
<div class="tijd">
date_default_timezone_set('GMT+1');
echo date('h:i');
$Tijd = date('h');
if ($Tijd > 12 || $Tijd <17') {
echo '<div class="Middag"> </div>';
}
if ($Tijd > 12 || $Tijd <17') {
echo '<div class="Avond"> </div>';
}
if ($Tijd >= '22') {
echo '<div class="Nacht"> </div>';
}
if ($Tijd >= '6') {
echo '<div class="Ochtend"> </div>';
}
echo('Dit is een test...')
?>
</div>
</body>
</html>
But, What is not working here? On the webpage it shows the time correctly but it doesnt show the background. It is also not working while i do a background color or something so i know it is not only the background color. I tried also to make a background in PHP but i kind of failed at that.
You should use if, else if:
if ($Tijd > 12 || $Tijd <17) {
echo '<div class="Middag"> </div>';
} else if ($Tijd > 12 || $Tijd <17) {
echo '<div class="Avond"> </div>';
} else if ($Tijd >= 22) {
echo '<div class="Nacht"> </div>';
} else if ($Tijd >= 6) {
echo '<div class="Ochtend"> </div>';
}
Having said that, your first two test conditions are exactly the same, so you should look at that too
(this should be a comment but its a bit long).
In addition to Marc B's comment, there's random quotes all over the place - don't quote numeric values when you're trying to do a numeric comparison. You're mixing HTML and PHP -
<?php
<div class="tijd">
This should be causing your code to throw big errors. If you're not seeing these errors then you need to investigate why.
And the way you are running multiple if statements is messy. You could use if...else if...else if ...else, but if you use a switch statement your code will be much clearer:
switch((integer)$Tijd) {
case 13:
case 14:
case 15:
case 16:
echo '<div class="Middag"> </div>';
break;
case 22:
case 23:
echo '<div class="Nacht"> </div>';
break;
default:
echo '<div class="Avond"> </div>';
break;
}
As you can see - there are gaps here which are not described by your original code.
<?php
$hour = date('H'); //H is for 24 hours interval
if ($hour > 4 && $hour < 6) {
$class = 'earlier-morning';
} elseif ($hour >=6 && $hour <=11) {
$class = 'morning';
} elseif ($hour >=11 && $hour < 15) {
$class = 'midday';
} elseif($hour >= 15 && $hour < 19) {
$class = 'day';
} elseif ($hour >= 19 && $hour < 22) {
$class = 'evening';
//the only one case left - hours between 22 and 4
} else {
$class = 'night';
}
echo sprintf('<div class="%s"></div>', $class);
The trick here is elseif
So only ONE condition will always work here.
P.S. I believe that extra quotes in your example is a typo ;-)

Categories