Could someone help suggest in below php explode function, we are displaying script after 5th listing. How is it possible to display script exactly after 5th listing and 10th listing on a page which has more than 10 listings
We tried using
if ($i == 5 & $i== 10)
but it does not work
Below is original code - which displays script after 5th listing
<?php
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 0; $i < $numberOfListings; ++$i)
{
if ($i == 5)
{ ?>
<script> </script>
<?php }
echo $listings[$i] . "<hr/>";
}
?>
Edit
How is it like - if have to display a separate script on $i==9, could you advise.
Because $i starts at 0 (0 to 9 is 10, whilst 0 to 10 is 11). Try if ($i == 4 || $i== 9), with an or operator.
Also I would not use the && (the and operator), because it is unlikely $i will ever equal both 4 and 9. I'd suggest you read into Truth Tables (and maybe Propositional Calculus) because from seeing what you had tried originally, it would be helpful to understand how a truth table works.
(source: wlc.edu)
You can use the contine, continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
$arr = range(0,9);
foreach($arr as $number) {
if($number < 5) {
continue;
}
print $number;
}
Ref: http://php.net/manual/en/control-structures.continue.php
Try using modulus operator
$listings = explode("<hr/>", $list);
$numberOfListings = count($listings);
for($i = 1; $i < $numberOfListings; ++$i)
{
if ($i%5 == 0)
{
echo "in";
?>
<script> </script>
<?php
}
echo $listings[$i-1] . "<hr/>";
}
Here we are looping from 1 and there for $i <= $numberOfListings
and while listing we will use $listings[$i-1]
DEMO CODE AT http://codepad.viper-7.com/lrTOgP
Related
Recently, my exams got over. My last exam was based on PHP. I got the following question for my exam:
"Convert the following script using for loop without affecting the output:-"
<?php
//Convert into for loop
$x = 0;
$count = 10;
do
{
echo ($count. "<BR>");
$count = $count - 2;
$x = $x + $count;
}
while($count < 1)
echo ($x);
?>
Please help me as my computer sir is out of station and I am really puzzled by it.
Well, If I understand well, You have to use "for" loop, instead of "do...while", but the printed text must not change.
Try:
$count = 10;
$x = 0;
$firstRun = true;
for(; $count > 1 || $firstRun;) {
$firstRun = false;
echo ($count . "<BR>");
$count -= 2;
$x = $x + $count;
}
echo ($x);
By the way loop is unnecessary, because $count will be greater than 1 after the first loop, so the while will get false.
EDIT
$firstRun to avoid infiniteLoop
$count in loop
EDIT
Fixed code for new requirement
Removed unnecessary code
Hmmm I don't know if your teacher wanted to own you... but the do{} will execute only once since $count is never < 1.
The output of your teacher's code is:
10
8
I presume there was a mistake in the code and the while would be while($count > 1) which would make more sense (since it's weird to ask for a loop to output only 10 8) and would result in this output:
10
8
6
4
2
20
Then a good for() loop would have been :
$x = 0;
$count = 10;
for($i = $count; $i > 1; $i -= 2)
{
$count -= 2;
echo $i . "<br>";
$x += $count;
}
echo $x;
Which will output the same values.
If you can, ask your teacher for this, and comment the answer ^^ ahahah
I'm somewhat new to PHP, been reading a few books and I've never seen a loop where it gets you all the even numbers(for example from 1 to 10), so I decided to try it myself:
for($i=0;$i<10 && $i % 2===0;$i++)
echo $i;
Tried with only double == as well.
And this,
$i=0;
do echo $i; while($i++<10 && $i % 2 ==0);
Can't seem to figure out how to use 2 conditions in the same statement.
Would appreciate the help!
Thanks.
Try to use this code
for( $i=0; $i<=10; $i++ )
{
if( $i%2 == 0 ){
echo $i;
}
}
The loop is breaking entirely when the second condition fails the first time. On the first iteration: 0 is less than 10, and it is even, so the loop iterates. On the second iteration: 1 is less than 10, but is odd, so the loop breaks.
Your code is the equivalent of this:
for($i=0; $i<10; $i++) {
if ($i % 2 !==0 ) {
break;
}
echo $i;
}
0
You can eliminate the second condition of your for loop to prevent the breakage and rely exclusive on a third expression to increment $i by two each iteration.
for($i=0; $i<10; $i = $i + 2) {
echo $i;
}
02468
The second statement in a for-loop is/are the condition(s) which gets checked every loop. so if it fails your loop stops. what you need will look somewhat like this:
for ($i = 0; $i < 10; $i++)
if ($i % 2 == 0)
echo $i;
So the loop will run over every number but only print out the even ones.
You don't need to loop.
Range can create a range with third parameter step 2.
$arr = range(0,20,2);
Echo implode(" ", $arr);
https://3v4l.org/S3JWV
you can use also regular loop and get the evens by formula:
for($i=0; $i<10 ;$i++) {
$j = $i * 2;
// do somthing with $j witch loop over 10 first evens...
}
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] ?
Newb question: I'm using a foreach loop to get items from an array.
I need to start looping at an offset number- (I'm using a $i variable to do this, no problem).
But when my foreach reaches the end of the array I want it to start going through the array again until it reaches the offset number.
I need to do this so I can have a user open any image in an artist's portfolio and have this image used as the first image presented in a grid of thumbnail icons , with all the other images subsequently populating the rest of the grid.
Any ideas?
Please bear in mind I'm new to PHP! :)
See below for an example of my current code...
$i=0;
$limit=50;// install this in the if conditional with the offset in it (below) to limit the number of thumbnails added to the page.
$offset=$any_arbitrary_link_dependant_integer;
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};// end of add thumbnails loop.
$i = 0;
$limit = 50;
$offset = $any_arbitrary_link_dependant_integer;
$count = count($portfolio_image_array);
foreach($portfolio_image_array as $k=>$image_obj){//$k = an integer counter, $image_obj = one of the many stored imageObject arrays.
$i++;
if ($i > $offset && $i < $limit && $i < ($count - $offset)) {// ignore all portfolio_array items below the offset number.
if ($img_obj->boolean_test_thing===true) {// OK as a way to test equivalency?
// do something
} else if ($img_obj->boolean_test_thing===false) { // Now add all the non-see_more small thumbnails:
// do something else
} else {
// error handler will go here.
}
} // end of offset conditional
}// end of add boolean_test_thing thumbnails foreach loop.
};
Only thing I added was a $count variable.
Edit: If your array starts at 0 I would suggest you put the $i++; at the end of your foreach loop.
A simple method is to use two separate numeric for loops, the first going from offset to end, and the second going from beginning to offset.
<?php
// Create an example array - ignore this line
$example = array(1,2,3,4,5,6);
$offset = 3;
// Standard loop stuff
$count = count($example);
for($i = $offset; $i < $count; $i++)
{
echo $example[$i]."<br />";
}
for($i = 0; $i < $offset; $i++)
{
echo $example[$i]."<br />";
}
?>
This is also almost certainly cheaper than doing multiple checks on every single element in the array, and it expresses exactly what you are trying to do to other programmers who look at this code - including yourself in 2 weeks time.
Edit: depending on the nature of the array, in order to use numeric keys you may first need to do $example = array_values($portfolio_image_array);.
Using Answer Question to force StackOverflow to let me post a decent length of text!
OK #Mark Walet et al, not sure how to post correctly on this forum yet but here goes. I got the issue sorted as follows:
$i=0;
$offset=$image_to_display_number;
$array_length = count($portfolio_image_array);
// FIRST HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from offset (chosen image) to end.
if ($i >= $offset && $i <= $array_length) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
$t_total++;// update thumbnail total count.
}
$i++;
}// end of foreach loop 1.
$looped=true;// Just FYI.
$i=0;// Reset.
// SECOND HALF LOOP:
foreach($portfolio_image_array as $k=>$img_obj){// go through array from beginning to offset.
if ($i < $offset) {
echo write_thumbnails_fun($type_of_thumbnail, $image_path, $k, $i, $portfolio_image_array, $title, $image_original);
}
$i++;
}// end of foreach loop 2.
Thankyou so much for all the help!
:)
as #arkascha suggested use modulo operator
<?php
$example = array(1,2,3,4,5,6);
$count = count($example);
$offset = 3;
for($i = 0; $i < $count; $i++) {
$idx = ($offset + $i) % count
echo $example[$idx]."<br />";
}
?>
I have a little script that prints a certain amount of rows in a mysql database.
Is there any way to make it so that after every second row it prints, there is a line break inserted?
Adding a line break after every row is simple, but I don't know how to add one after every other row. Is that possible?
You write "script" but in tags you have PHP, so I suppose you need PHP code:
foreach ($rows as $row) {
if ($i++ % 2) {
// this code will only run for every even row
}
...
}
$i=1;
while ($row = mysql_fetch_array($query))
{
//your code
if ($i % 2 == 0)
echo '<br>';
$i++;
}
add new variable before the loop
$i = 0;
then in your loop add
if ($i != 0 && $i%2 == 0)
echo '<br/>';
Depending on the language, something like this should do it: (in php) (where $arr is an array of results)
$str = '';
$i = 0;
for ($i=0; $i<count( $arr ); $i++)
{
if ( ( $i + 1 ) % 2 === 0 )
{
$str .= $arr[$i] . '<br />';
}
else
{
$str .= $arr[$i];
}
}
echo $str;
Use php and modulo.
such as
if($i % 3)
{
echo '<br />'..
If you need to do this inside the query for some reason, you could use something like
SELECT
<your fields>,
IF (((#rn:=#rn+1) % 3)=0,'<br>','') as brornot
FROM
<your tables and joins>,
(#rn:=0)