What I'm doing is for every 3rd outputted MySQL database row, I'll run a custom function that outputs differently. How would I identify every 3rd row?
Very simple. You can do something like this:
$i = 1;
while ( $array = mysql_fetch_assoc($result) )
{
if ($i % 3 == 0)
{
// call other function
}
$i++;
}
Please, note the use of the modulus operator.
This will call the specific function every 3rd row
$cpt = 1;
while ($row = mysql_fetch_assoc($result)) {
if($cpt % 3 == 0){
do_something_custom();
}
$cpt++;
}
I guess this will be kinda repeating the others , but :
$i = 1;
while ( $data = $pdo_statement->fetch( PDO::FETCH_ASSOC ) )
{
if ( $i++ % 3 === 0 )
{
// do stuff
}
}
Related
If I wanted to create a foreach loop that would add every second player to team A or team B
foreach ( $selectedplayers as $selectedplayer ) {
TeamA[] = $selectedplayer;
$selectedplayer++;
TeamB[] = $selectedplayer;
}
I know I can do it with a for loop but was interested to see if it could be done this way.
No. $selectedplayer is the actual value of each element. Either use your own counter:
$i = 0;
foreach ( $selectedplayers as $selectedplayer ) {
if($i % 2 === 0)) {
$TeamA[] = $selectedplayer;
} else {
$TeamB[] = $selectedplayer;
}
$i++;
}
Or use the $key of the array if the keys are sequential (or at least odd, even pattern):
foreach ( $selectedplayers as $key => $selectedplayer ) {
if($key % 2 === 0)) {
$TeamA[] = $selectedplayer;
} else {
$TeamB[] = $selectedplayer;
}
}
I am looping a foreach and i need to make some logic like this:
if the iteration is not the last. Gather up the prices. when the iteration is the last. subtract from the total with the gathered up prices. except the last iteration price. I got the following code not. but it's not working.
$i = 0;
$credit = '';
$count = count($reslist);
foreach ($reslist as $single_reservation) {
//All of the transactions to be settled by course
//$credit = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
if ($i > $count && $single_reservation != end($reslist)) {
$gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
$credit = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
}
//Last iteration need to subtract gathered up sum with total.
else {
$credit = $suminczk - $gather_sum_in_czk;
}
$i++;
}
EDIT: TRYING TO GATHER UP PRICES FOR ALL INTERACTIONS EXECPT LAST:
if ($i != $count - 1 || $i !== $count - 1) {
$gather_sum_in_czk += $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
$credit = $this->Reservations_model->find_res_price($single_reservation['value']) * $this->input->post('currency_value');
}
else {
$credit = $suminczk - $gather_sum_in_czk;
}
The SPL CachingIterator is always one element behind its inner iterator. It can therefore report whether it will produce a next element via ->hasNext().
For the example I'm choosing a generator to demonstrate that this approach doesn't rely on any additional data like e.g. count($array).
<?php
// see http://docs.php.net/CachingIterator
//$cacheit = new CachingIterator( new ArrayIterator( range(1,10) ) );
$cacheit = new CachingIterator( gen_data() );
$sum = 0;
foreach($cacheit as $v) {
if($cacheit->hasNext()) {
$sum+= $v;
}
else {
// ...and another operation for the last iteration
$sum-=$v;
}
}
echo $sum; // 1+2+3+4+5+6+7+8+9-10 = 35
// see http://docs.php.net/generators
function gen_data() {
foreach( range(1,10) as $v ) {
yield $v;
}
}
foreach-ing an array in PHP returns both the key (integer index if pure array) and value. To be able to use the value, use the following construct:
foreach ($array as $key => $value) {
...
}
then you can check whether $key >= count($array) - 1 (remember in a 0-based array, the last element is count($array) - 1.
Your original code almost works, just wrong in the if condition. Use $i >= $count - 1 instead of $i > $count.
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,";
}
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 have a xml file with 100 records, but I want it to limit it to just 5 records
for ($i=0;$i<=5;$i++) {
foreach($xml->entry as $result){
if ($result->updated == $result->published) {
}
}
}
When I put in the above code, it display one record 5 times.
Thanks
Jean
$count = 0;
foreach($xml->entry as $result)
{
if ($result->updated == $result->published) {
}
$count++;
if ($count++ == 5) break;
// if ($count++ == 5) break; think this might work aswell
}
It seems that the foreach loop runs only once, because there is only one entry, and the for loop prints it 5 times. If there were more than one, this code would print each entry 5 times. If $xml->entry is an array, you can do it like this:
for($i = 0; $i < 5; $i++) {
$result = $xml->entry[$i];
if($result->updated == $result->published) {
}
}
Check if there are more than one <entry> tags in your XML file.