While Loops and Multiple Conditions - php

Is it possible to write multiple conditions in a while loop? If not, what is an alternative? I tried it and was returned with an error relating the line of code that sets up the conditions for the while loop. Here is an example of what I mean.
$s = 1;
while ($result_row = mysql_fetch_assoc($query) && $s < 5)
{
echo $result_row['id'];
$s++;
}

That is possible, but because = has lower precedence than && you need parentheses to ensure that your statement is interpreted correctly:
while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))
The parentheses around $s < 5 are not required here, but I've included them for clarity.
However it would be easier just to modify your query to only return 5 rows, by adding LIMIT 5.
SELECT ...
FROM yourtable
ORDER BY ...
LIMIT 5

You could try:
$s=1
while ($result_row = mysql_fetch_assoc($query))
{
echo $result_row['id'];
$s++;
if($s>5){
break;
}
}
http://php.net/manual/en/control-structures.break.php

while i see nothing wrong in that. the other way round is to do something like this.
$s = 1;
while ($result_row = mysql_fetch_assoc($query))
{
if($s < 5) {
//enter the condition
}
$s++;
}

The value of $result_row is probably being set to the Boolean condition of whether mysql_fetch_assoc($query) returns something true-ish and $s is less than 5. So trying to read $result_row as a dictionary no longer works.
You can use parenthesis to specify exactly how things get parsed:
while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))
This way, $result_row gets set to mysql_fetch_assoc($query), which is what you want, and the loop continues as long as the logical value of that assignment returns something true-ish, as well as s is less than 5.

Related

Multiple counters not counting ( foreach / ifs)

This is my first StackOverFlow post.
I have an array of numbers, which I shuffle:
$nums = array("1","1","1","1","1","2","2","2","2","3","3","3","4","4","4");
shuffle($nums);
I am trying to identify a sequence/pattern of any three 3 identical numbers in a row in the shuffled array and
output the combined total of all sets of matching numbers.
The problem that I am running into seems to stem from attempting to compare the current number in the loop with the previous number (to see if they match).
When I echo the "previous" number it always outputs as "0". Thus I am unable to compare the current number and old number, which means I am not able to sum identify and sum a pattern of identical numbers.
Here is my code:
<?php
$t3count = 0;
$oldnum = 0;
$tots = 0;
$nums = array("1","1","1","1","1","2","2","2","2","3","3","3","4","4","4");
shuffle($nums);
foreach ($nums as $num) {
echo "$num: [$oldnum] ";
if ($num = $oldnum) {
$t3count++;
if ($t3count = 3) {
$tots = $num * $num;
$t3count = 0;
$oldnum = $num;
} else {
# do nonum
}
}
else {
$oldnum = $num;
}
# echo "<li>$num</li>";
}
echo "Your total is: $tots";
unset($num);
?>
Thank you.
You need to do comparison == not assignment = here:
if ($num = $oldnum)
and here:
if ($t3count = 3)
also this is probably going to bite you if i got the logic right
$t3count++;
if ($t3count == 3) {
how do you know which one counted to 3, id build nested arrays of like values first then process that.
you missed == to compare if ($num = $oldnum) and if ($t3count = 3)
replace with
if ($num == $oldnum)
if ($t3count == 3)

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.

counting results within a if/else statement

I am trying to sum the total results in an if/else statement. so the $result (in there for example) would appear 4 times. I have tried count($result), this doesnt work.
while ($sq=mysql_fetch_array($query)){
if ($avg > $btmspeed && $avg < $topspeed){
$result;
}else{
}
}
Basically I am running a while loop through some database results and these existing variables would give 4 results through the if statement and I want to reflect that. I know its probably and easy answer but banging head against a wall and search engines havent given me the answer. please help!
Use a counter.
Var i=1;
Outside of the loop.
Inside the loop add:
i++;
Do you just need to move the $result declaration outside the loop and increment it inside the 'if' block?
$result = 0
# loop starts here
if ($avg > $btmspeed && $avg < $topspeed){
$result = $result + 1
} else{
}
Assuming your result is a number. You would loop over whatever it is I assume an array with information, where you'd be checking the if-else like you originally provided.
$i = 0;
for($x=0; $x < $result; $x++;)
{
if ($avg > $btmspeed && $avg < $topspeed){
$i++;
}else{
}
}
echo $i;

error using compare code

If i've database my_table (id,word) as following
and i've some posted text called $name then i want to know if $name have any word like words i've stored in my database my_table (id,word)
so i'm using this code
$name = "Hello lovely world"; // no bad words
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$commentArray = explode(" ", $name);
$counter = count($commentArray);
$check = 0;
while ($row = mysql_fetch_assoc($result)) {
for ($i == 0; $i < $counter; $i++) {
if (strcasecmp($commentArray[$i], $row['word'])) {
$check = 1;
}
}
}
if ($check == 1) {
echo "banned";
exit;
}
else {
echo "passed";
}
however it always results in echo "banned"; even if i $name is clear of any bad words i've stored in my_table so there might be something wrong here !
anyhelp
strcasecmp returns 0 when it matches (PHP manual), so you should edit your code:
if (strcasecmp($commentArray[$i], $row['word']) == 0)
Furthermore, you have a syntax error in your for loop. It should be for ($i = 0; ...
You have a syntax error.
for ($i = 0...
And not
for ($i == 0...
Also, you should indent your code properly, it looks better and it'll help you later on.
The thing is strcasecmp returns 0 if the strings are equal. You ought to change it to if (strcasecmp($var1, $var2) == 0).
As a starting point, I'd suggest storing only lowercased words in the table, lowercasing the input text first, and then replacing the whole strcasecmp loop with an in_array($row['word'], $commentArray);. And break; after the first match.
But this entire approach doesn't scale - you're selecting all the entries in the table. If your table grows beyond a certain size, that will be a serious bottleneck and you'll need to look into matching on the DB side.

Categories