Add An If statement to a value using php - 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;
}

Related

PHP - make if statement with two statements shorter

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.

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] ?

php function to check if number is divisible by 0

I have checked a bunch of posts on stackoverflow and on articles on google but none of them were able to answer my question. Here is my code (i've simplified it instead of posting my code)
$first = 10;
$second = 0; //comes from db row count
$total = !is_int($first/$second) ? 0 : $first/$second;
problem is when i do this I keep getting the Division by zero error. I have a bunch and $second isnt always 0, it can be any number. But it does come out to 0 since the row counts for whatever query it comes out as 0. Is there a safe way of checking to see if $first can be divided by $second without giving an error? I have tried # before the !is_int and that just breaks all other statements.
Try this:
$total = ($second == 0) ? 0 : $first / $second;
You can't divide by 0 it is undefined. If you want to handle division by 0 just check if the divisor isn't equals to 0. Or a safer way, chack if it is a positive integer:
$first = 10;
$dbRowCount = dbFunction();
if ($dbRowCount > 0) {
$total = $first / $dbRowCount;
} else {
//Error handling
}
The ternary structure can accept more than one condition. and it will work just as any other if condition, and won't try the second condition if the first fails.
So, just add it
$total = ($first!==0 && $second!==0 && !is_int($first/$second)) ? 0 : $first/$second;
You might want to try checking if your $Second variable is 0.
Something like:
$First = 10;
$Second = $row['table_column'];
if ($Second == 0) {
echo "Oops this will be an error";
}
else
$First/$second = $me;

Can you help me get this PHP explode/array/numrows/etc block working?

Ok, so here's my code:
if ($_GET['send'] === "yes") {
$name = $_POST['msg-to'].", ";
$nameParts = explode(", ", $name);
$recipients = array();
for ($x = 0; $x >= 10; $x++) {
$name_query = mysql_query("SELECT * FROM users WHERE username='".$nameParts[$x]."'");
while($value = mysql_fetch_array($name_query)){ $name_numrows = mysql_num_rows($name_query); }
if ($name_numrows = 1) {
$recipients[$x] = $nameParts[$x];
$msgError .= '<span class="success">'.$nameParts[$x].' is a valid user.</span><br>';
} else {
$msgError .= '<span class="warning">'.$nameParts[$x].' is not a valid user, message did not send.</span><br>';
break;
}
}
}
But when a user enters a username for this message to be sent to, it doesn't seem to work AT ALL. It doesn't echo either of the two error messages, and doesn't return an error. It doesn't do anything.
Any feedback at all would be absolutely wonderful :D
I tried to help in the comments above but I think a more clear explanation is needed so I'm resorting to posting an answers. Your code:
for ($x = 0; $x >= 10; $x++) {
This code block declares $x = 0 as the first part of the statement, this is the initialisation.
The second part $x >= 10 is the condition. It states that while $x is greater than or equal to 10 you want to execute an iteration of the loop.
The final part $x++ is the afterthought. It states that on each successful iteration of the loop you want to increment the value of $x.
Because you initialise $x to be 0 and then set the condition that it has to be greater than or equal to 10 >= 10 the condition will fail first time, every time. 0 can't be great than or equal to 10. I imagine what you probably want for your condition is something like while $x is less than or equal to 10 $x <= 10.

Double equals in for loop?

Why doesn't the double equals work in a PHP for loop? The following works:
$cnt = 5;
for ($z = 0; $z <= $cnt; $z++) {
echo $z."!<br />";
}
But why doesn't this work?
$cnt = 5;
for ($z = 0; $z == $cnt; $z++) {
echo $z."!<br />";
}
The loop executes only if the condition evaluates to true. At the first iteration, $z == $cnt is false, so the loop never executes.
A common loop strategy is to use a sentinel value:
$cnt = 5;
$stop = $cnt + 1;
for ($z = 0; $z != $stop; $z++) {
. . .
}
Note that the comparison is negative (!= or !==). Using a sentinel is usually unnecessary for numerical loop variables (I wouldn't recommend it for your posted code), but is useful for other situations (e.g., when $stop represents null, an illegal value, etc.). It's particularly helpful when the loop variable changes in a pattern that is not easy to characterize succinctly.
because on the first iteration $z != $cnt, so the loop stops immediately.
Let us look at this from the computer's perspective:
If I am a computer this is what you told me to do:
set $cnt = 5;
set $z = 0;
check if $z equals $cnt
if so do whatever is in the loop, then increment $z
Trouble is, 5 does not equal 0 and never will, so the loop will simply be skipped. If you had $cnt = $z+1 inside the loop this would be an infinite loop.
So, you see, == works just fine, it simply doesn't do what you think it should do.
Hope this helps!
A for loop works by looping until a condition is made false. In the first example the loop will execute until z = 5 after that z will not longer be less than or equal to cnt (z starts at 0 and increments through each loop). In the second example you have $z == $cnt as your condition, and since z = 0 and cnt = 5 the loop will stop automatically because the condition is made false. You can use not equals instead like following:
$cnt = 6;
for ($z = 0; $z != $cnt; $z++) {
echo $z."!<br />";
}
The syntax of for is:
for (<init>; <condition>; <increment>)
The loop tests <condition> before each iteration. If it's true, it executes that iteration; if it's false, the loop terminates.
In your case, since $z == $cnt is false before the first iteration, the loop terminates immediately.
To do what you want, invert the test. You also need to bump the end value up by one, since the original version used <=, not <. Note that in both cases, the loop executes $cnt+1 times, because you start from 0.
for ($z = 0; $z != $cnt+1; $z++)

Categories