PHP - make if statement with two statements shorter - php

I have the following If statement and I want to make it shorter (eg. a one liner), without writing my if statement in one line.
if ($start + $count > $total) {
$count = $total;
}
Basically I want to achieve that $count + $total is never higher then $total and if this is the case I want to set $count equal to $total.

You can use min() for that:
$count = min($total, $start + $count);

What you want is called a ternary operation.
$count = (($start + $count) > $total ? $total : null);
References:
https://davidwalsh.name/php-shorthand-if-else-ternary-operators
http://php.net/manual/en/language.operators.comparison.php
https://www.abeautifulsite.net/how-to-use-the-php-ternary-operator

You could use the ternary operator.
$count = ($total < $start+$count) ? $total : $count;
This puts the if-logic in one line.

Related

Add An If statement to a value using php

how do i add an if statement to a Php value, this is what i tried
&n = 1;
$number = if(10 < 1)
{
$n = 0;
}
is there any way to fix this or something i didn't ad that made it not to work?
because it kept showing an error message that the code is not right
You have a typo and some syntax error.
&n = 1;
That should be:
$n = 1;
Also, you can't really assign the value of an if statement to your variable.
Try simply using a ternary instead.
$n = (10 < 1) ? 1 : 0;
In PHP, if is a statement, but the = operator expects an expression, so that is invalid syntax. If you want to assign something to $number when the condition is true, then you can use something like:
if (10 < 1)
{
$number = ...;
$n = 0;
}

For LOOP taking time to execute in PHP

I am taking a demo test at codility.com.
I tried the following PHP test code:
function solution($A) {
$min = 0;
$size = count($A)-1;
for($i=0;$i<5;$i++){
if($i=0)
$min=$A[0];
}
return $min;
}
The script takes around 3.03s to execute where they have set the maximum execution time to 2.00s.
And if i comment the FOR LOOP it works properly.
Any idea ?
You are overwritting your $i variable here:
if($i=0)
it should be
if($i==0)
because you have wirte if($i=0) it is assignment operator not comparision operator. make it correct if($i==0)
function solution($A) {
$min = 0;
$size = count($A)-1;
for($i=0;$i<5;$i++){
if($i==0)
$min=$A[0];
}
return $min;
}
Your for loop looks like this:
for($i = 0; $i < 5; $i++)
This means: initialize $i to 0, and until $i is 5 or more, execute the loop and increment $i.
But, you wrote this:
if($i = 0)
To compare $i and 0, you should've used ==, not =. This sets $i to 0. The if is not executed, as 0 is equal to false. Then $i is incremented to 1. 1 is less than 5, so the loop is executed forever.
Use if($i == 0) to fix it.
There is a mistake that everyone has pointed out which is if($i=0) should be if($i==0).
But I have one concern. Why there is a for loop when it is simply returning $min which is $A[0] ?

trying to understand while loop in PHP

I am trying to run the while loop until it equals to thirty.
<?php
$num1=0;
$num2=0;
$sum= $num1 + $num2;
while($sum=30){
$num1++;
$num2++;
echo "$sum is equal to 30";
}
?>
You need to change while($sum=30) to while($sum<30).
Then, the while loop will end after you reached 30. The echo then comes after the closing bracket.
Sp your working code will look like this:
while( $sum < 30 )
{
$num1++;
$num2++;
$sum = $num1 + $num2;
}
echo "sum is $sum (which is 30)";
You are calculating the sum outside the while loop, so inside the loop the $sum never changes. You have to calculate the sum inside the loop. also = is assignment operator. you must use comparison operator to compare.
$num1=0;
$num2=0;
$sum=0; //initilize you sum to 0
while($sum<30){ // loop while your sum is less than 30
$sum= $num1 + $num2; //calculate the sum
$num1++;
$num2++;
}
echo "$sum is equal to 30";
?>
Reference:Comparison Operators
use equality operator (==) not assignment operator (=)
This loop not ends. $sum ever is 0 !.
$num1=0;
$num2=0;
$sum= $num1 + $num2;
$x = 0;
while(!$x && $sum <=30){
$num1++;
$num2++;
$sum= $num1 + $num2;
if($sum ==30){
echo $sum." is equal to 30";
$x = 1;
}
}
Try this! Have a nice day !!

Using for loop instead of if statement?

I am trying to familarise myself with for loop as I only understand the basics.
I am trying to simplify the code below
$round1 = $max / 2;
$round2 = $round1 + ($max / 2 / 2);
$round3 = $round2 + ($max / 2 / 2 / 2);
$round4 = $round3 + ($max / 2 / 2 / 2 / 2);
$round5 ...
With this:-
$round = array($max/2);
for ($i=1;$i<$max;$i++) {
$round[] = $round[$i -1] + $max/pow(2, $i + 1);
}
And now for the next code:-
if($matchno <= $round[0]) {
$scores_round1.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[0] AND $matchno <= $round[1]) {
$scores_round2.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[1] AND $matchno <= $round[2]) {
$scores_round3.= '['.$score1.', '.$score2.'],';
}
if($matchno > $round[2] AND $matchno <= $round[3]) {
$scores_round4.= '['.$score1.', '.$score2.'],';
}
Can the above be used in a for loop to avoid using if() ?
Thanks for help
You can check for round1 and for the rest:
for ($i=1;$i<$max;$i++) {
if($matchno>$round[$i] AND $matchno <= $round[$i+1])
${'scores_round'.$i}.='['.$score1.', '.$score2.'],';
}
for($i=0;$i< count($round); $i++){
if($match < $round[$i]){
${"scores_round".$i}.= '['.$score1.', '.$score2.'],';
break;
}
}
By watching the if statements, we notice some things:
First of all, there is no *else if* statement. That means that all if statement checks must be executed.
Additionally, there is a check whether the $matchno is less than $round[0], without any check for greater than in this if statement (the first one).
Another point is that $scores_roundX starts with X=1 and not 0.
Obviously, you will have to use one if inside the loop.
So, we are going to form loop code making some small tricks:
for($i = -1; $i < count($round)-1 ; ++$i){
if(($i = -1 OR $matchno > $round[$i]) AND ($matchno <= $round[$i+1])){
${"scores_round".$i+2} .= '['.$score1.', '.$score2.'],';
}
}
We will initialize THE $i with -1, to use it for the first statement execution.
We will put as for statement the $ to be less than the count of the
array minus 1 (because we index using $i+1 in our if statement,
inside the loop).
We will perform greater than check only if the $i is not -1, and this
will happen on the second check (second if in initial code). Here, we also use
the partial evaluation feature of the language, and that means that in the OR sub-statement,
if the first part comes as true, the second one is not ecaluated.
We will make $i+2 at the $scores_round forming, because we start from
-1 on our for loop.

Variable merging which doesn't make sense

Consider this code:
$x = 1.4;
$i1 = 0.5;
$i2 = 0.4;
echo ($i1 + $i2 = $x); // Outputs 1.9
Why is this? I've tried searching for this kind of variable setup without results. Is the variable $i2 being ignored? Why use this over echo ($x + $i1);? It outputs the same result.
The point is that it does two things in one statement.
It is shorthand for:
$i2 = $x;
echo ($i1 + $i2);
The assignment happens inline, saving the separate line. Not ideal style, but often used in if(), while() and other control statements.
that would be $i1 + the assignment.
The assignment evaluates to $x ($i2 = $x )
the end result is echo 0.5 + 1.4.
Even php has operator priorities http://php.net/manual/en/language.operators.precedence.php.
= is treated before +, which means that this is what happens:
echo ($i1 + ($i2 = $x));

Categories