I'm a beginner learning PHP. I have tried to make a loop that has a different behaviour for both even and odd numbers. I've been playing around with it for a while, yet I still can't get it to work. Has anyone got a solution?
$count = 0;
$mod = $count % 2;
while ($count < 10)
{
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
A silly mistake, mod inside while() loop.
$count = 0;
while ($count < 10) {
$mod = $count % 2; //Here
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
$count = 0;
$mod = $count %2;
Is were your problem is.
You have to use the modulus (%) operator inside the for loop. Also, there is no need to store the value from the use of the modulus operator at all, it can be compared directly inside the for-loop.
for ($count = 0; $count < 10, $count++) {
if ($count % 2 == 0) {
echo "even, ";
} else {
echo "odd, ";
}
}
You can also switch the while to a for like this.
Welcome to PHP.
Edit #1:
As you are getting a new value of $count every execution of the for-loop the old value if $count % 2 will be incorrect. It has to recalculate for every $count. First it checks if 0 is divisible by 2, then onto 1 and so forth. For every value of $count you have to check the divisibility.
In most programming languages you aren't computing a variable onto another, instead you are taking the value of the variable. Like $a = $b + $c; in that case, if you change the value of $b or $c it does not automatically update $a. Instead you have to call $a = $b + $c again. It is the same with % operator.
$count = 0;
while ($count < 10) {
$mod = $count % 2;
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
use for loop instead of while loop
for($count=0;$count<10;$count++)
{
if(($count % 2) == 0)
echo "even,";
else
echo "odd,";
}
Related
im trying to create a script that generates a number and depending on the number generated it prints something specific but it's not working properly, Heres the code:
<?php
for($zz = 1; $zz <= 20; $zz++) {
$rangen = rand(1,100);
$a = (1 <= 0) && (0 <= 7);
$b = (8 <= 0) && (0 <= 17);
echo ("<br>".$rangen . "<br>");
if($a) {
echo "a";
} elseif ($b) {
echo "b";
} else {
echo "c";
}
}
?>
The error is that it keeps printing "c" no matter what the number is.
If anyone could help that would be great, thanks.
Your conditions are all wrong. Your comparing the same numbers and never using $rangen, this is why you obtain the same result each time.
1 <= 0 and 8 <= 0 will always return false which is why you always go to the else statement.
I have the following bit of code and for some reason in the first WHILE loop the first value of $actor_list (when $i = 0) does not display. If I simply echo $actor_list[0] then it displays fine, but in the loop it will not display. I merely get [td][/td] as the output. The remaining values of the array display fine.
Also the line
echo '</tr><tr> </br>';
is not displaying.
What am I missing here? The value of $num_actors is an even number in my test scenario so there doesn't seem to be a reason for the above echo line to be skipped.
$actor_list = explode(" ", $actors);
$num_actors = count($actor_list);
if ($num_actors <= 6) {
foreach ($actor_list as $actor) {
echo '[td]'.$actor.'[/td] </br>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
echo '</tr><tr> </br>';
while ($i <= $num_actors) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
}
}
You're not initialising the variable $i to 0, which means it will be set to 'null' and thus not reference the 0th index of the array; but when it's then incremented its value will become 1.
Note: [..] Decrementing NULL values has no effect too, but incrementing them results in 1.
See: http://php.net/manual/en/language.operators.increment.php
Try adding:
$i = 0;
before the if statement.
Made a few changes.
This is working for me.
Try it out.
<?php
$actor_list = 'act1 act2 act3 act4 act5 act6';
$actors = explode(" ", $actor_list);
$num_actors = count($actor_list);
//debug
//echo "<pre>";
//print_r($actor_list);
//echo "</pre>";
echo "<table>";
if ($num_actors <= 6) {
foreach ($actors as $actor) {
echo '<tr><td>'.$actor.'</td></tr>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
while ($i <= $num_actors) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
}
}
echo "</table>";
?>
When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.
I got the answer fine, but when I run the following code,
$total = 0;
$x = 0;
for ($i = 1;; $i++)
{
$x = fib($i);
if ($x >= 4000000)
break;
else if ($x % 2 == 0)
$total += $x;
print("fib($i) = ");
print($x);
print(", total = $total");
}
function fib($n)
{
if ($n == 0)
return 0;
else if ($n == 1)
return 1;
else
return fib($n-1) + fib($n-2);
}
I get the warning that I have exceeded the maximum execution time of 30 seconds. Could you give me some pointers on how to improve this algorithm, or pointers on the code itself? The problem is presented here, by the way.
Let's say $i equal to 13. Then $x = fib(13)
Now in the next iteration, $i is equal to 14, and $x = fib(14)
Now, in the next iteration, $i = 15, so we must calculate $x. And $x must be equal to fib(15). Now, wat would be the cheapest way to calculate $x?
(I'm trying not to give the answer away, since that would ruin the puzzle)
Try this, add caching in fib
<?
$total = 0;
$x = 0;
for ($i = 1;; $i++) {
$x = fib($i);
if ($x >= 4000000) break;
else if ($x % 2 == 0) $total += $x;
print("fib($i) = ");
print($x);
print(", total = $total\n");
}
function fib($n) {
static $cache = array();
if (isset($cache[$n])) return $cache[$n];
if ($n == 0) return 0;
else if ($n == 1) return 1;
else {
$ret = fib($n-1) + fib($n-2);
$cache[$n] = $ret;
return $ret;
}
}
Time:
real 0m0.049s
user 0m0.027s
sys 0m0.013s
You'd be better served storing the running total and printing it at the end of your algorithm.
You could also streamline your fib($n) function like this:
function fib($n)
{
if($n>1)
return fib($n-1) + fib($n-2);
else
return 0;
}
That would reduce the number of conditions you'd need to go through considerably.
** Edited now that I re-read the question **
If you really want to print as you go, use the output buffer. at the start use:
ob_start();
and after all execution, use
ob_flush();
flush();
also you can increase your timeout with
set_time_limit(300); //the value is seconds... so this is 5 minutes.
I'm terribly confused on how I should be writing this function...it basically scores a test, and it WORKS for one user's values.
Let's say I want the values for the following user: $id = 2...this works! If $id = array(2,3,4,5) it doesn't work!
function get_score_a($id){
// Case 4
foreach($this->get_results_a($id,4)->row() as $key=>$a){
if ($a >= 2 && $a <= 4) {
$score_a += 2;
} else if ($a > 4 && $a < 8) {
$score_a += 3;
} else if ($a > 8) {
$score_a += floor($a - 8) * .5;
$score_a += 3;
}
};
return $score_a;
}
function get_results_a($id, $method) {
$select_cols = array(
1 => array('a_1','a_2','a_4'),
2 => array('a_6','a_8','a_11','a_12','a_14'),
3 => array('a_3','a_10'),
4 => array('a_5','a_7','a_9','a_13')
);
return $this->db->select($select_cols[$method])
->where_in('id', $id)
->get('be_survey');
}
This returns a score...however, if I run multiple ids...it just adds up all the numbers, I think...
Instead I need this to output separate scores for individual users...
May it be noted that I'm a total noob! So vivacious explanations are very much appreciated. :)
Edit
Please review my code...as I should have been more clear! Sorry!
I apologize! In summation, this selects the correct values from the table, based on
And yes, my eyes hurt too!
Edit
I am too hasty! This is a Codeigniter project!
Firstly, there is no row() for arrays.. just use foreach ($array as $key=>$value)
Secondly, inside the foreach loop $score_b is being incremented on each run with its previous value. So, your code is outputting the sum of all player scores.
use:
foreach(array(5,5,5,6,7,78,8,7,7,6,5) as $key=>$a){
if ($a >= 0 && $a <= .5) {
$score_b[$key] += 0;
} else if ($a > .5 && $a < 2) {
$score_b[$key] += 1;
}
else if ($a > 2 && $a < 4) {
$score_b[$key] += 2;
}
else if ($a > 4) {
$score_b[$key] += floor($a - 8) * .5;
$score_b[$key] += 2;
}
};
$score_b will now be an array of scores.
EDIT:
Add the following in your code:
$id = array(2,3,4,5);
function get_score_array($ids) {
foreach ($ids as $id) {
$scores[$id] = get_score_a($id);
}
return $scores;
}
$scores will now be an array of $id=>$score pairs.
Also, adjust the above code, as per your framework (which I guess you are using)
There is no such method called row() on array. In fact, an array isn't strictly an object, so it doesn't have methods.
So, first of all, get rid of the ->row() invocation.
Second, where are you pushing these scores onto an array? I don't see where that happens in your code. Initialize an empty array before the foreach loop, and push the $score_b variable onto the array at the end of the loop.
Set a $userID variable outside the foreach loop like this:
$userScores = array(
'bobby' = > array(5,5,5,6,7,78,8,7,7,6,5),
'sue' = > array(5,5,5,6,7,78,8,7,7,6,5),
'joe' = > array(5,5,5,6,7,78,8,7,7,6,5)
);
foreach($userScores as $name => $a){
$score_b[$name] = 0; //initialize
if ($a >= 0 && $a <= .5) {
$score_b[$name] += 0;
} else if ($a > .5 && $a < 2) {
$score_b[$name] += 1;
}
else if ($a > 2 && $a < 4) {
$score_b[$name] += 2;
}
else if ($a > 4) {
$score_b[$name] += floor($a - 8) * .5;
$score_b[$name] += 2;
}
};
your end result should be something like (I didn't do any actual math)
$score_b['bobby'][100]
$score_b['sue'][75]
$score_b['joe'[90]