Create HTML elements in loop - php

Given a number like i.e: 6 I need to generate 6 DIV elements.
For example:
$number = 6;
// PHP generates the DIV for $number of times (6 in this case).
How can I do it? I am not an expert of PHP loops, if this is the case. Thanks!

Example uses of the different types of loops you could use. Hopefully you can see how they work.
Foreach Loop
$element = "<div></div>";
$count = 6;
foreach( range(1,$count) as $item){
echo $element;
}
While Loop
$element = "<div></div>";
$count = 0;
while($count < 6){
$count++;
echo $element;
}
Simple For Loop
$element = "<div></div>";
$count = 6;
for ($i = 0; $i < $count; $i++) {
echo $element;
}

function generateDIVs($number)
{
for ($i = 0; $i <= $number; $i++)
{
echo "<div><div/>";
}
}

In order to generate 6 div elements loop is necessary.
using while loop:
$count = 1;
while($count <= 6){
$count++;
echo "<div></div>";
}
using for loop:
$count = 6;
for ($i = 0; $i < $count; $i++) {
echo "<div></div>";
}

for ($i = 0; $i < 6; $i++) {
echo "<div class=\"example\"></div>";
}
Note that IDs (the # part) have to be unique on a page, so you can't have 6 different divs with the same #example id.
http://php.net/manual/en/control-structures.for.php

Here are some examples I use often, for quick mock-upping repeated HTML while working with PHP
array_walk() with iteration index and range
$range = range(0, 5);
array_walk($range, function($i) {
echo "
<section class='fooBar'>
The $i content
</section>
";
});
If tired of escaping double quotes \" or using ' or concatenation hell, you could simply use Heredoc.
$html = function($i) {
echo <<<EOT
<section class="fooBar">
The $i content
</section>
EOT;
};
array_map($html, range(1, 6));
The only small "disadvantage" of using Heredoc is that the closing EOT; cannot have leading and following spaces or tabs - which might look ugly in a well structured markup, so I often place my functions on top of the document, and use <?php array_map($html, range(0, 5)) ?> where needed.
str_repeat() when an index is not needed
$html = "
<section class='fooBar'>
Some content
</section>
";
echo str_repeat($html, 6);

you need echo command. Basically you are generating html by printing a string. Example
echo '<div> </div>';
will generate 1 div. You need it 6 times. You might want to use loop as well, but this is too basic question and I gave you a start.

Related

PHP Array, Get every 4 results and output in a loop

I'm trying to output my array results in groups of 4.
<?php for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } ?>
The above does 4, but obviously doesn't re-loop.
You can loop whole array and group you output with help of "%" operator.
<div>
<?php for ($i = 0; $i < count($array); $i++) {
if (($i % 4) == 0) {
echo "</div><div>";
}
echo "Element " . $array[$i]; // CODE
}
</div>
Other than using Mod as the other answers show, you could use array_chunk() to create the groups:
$groups = array_chunk($original_array, 4);
foreach($groups as $group){
echo '<div>';
foreach($group as $item){
echo $item;
}
echo '</div>';
}
You can use a while loop to reloop for the whole results to be printed
<?php while(conditions) {
for ($i = 0; $i < 4; ++$i) { ?>
<div>
// code
</div>
<?php } } ?>
Try this that way you can jump by 4
for ($i = 0; $i < 20; $i = $i+4) {
echo $i.'<br/>';
}
I would use a foreach and then just throw in an extra check to output the divs.
$i=0;
foreach ($array as $key->$val)
{
if($i%3==0)
{
echo "<div>";
}
// your stuff
if($i%3==0)
{
echo "</div>";
}
$i++;
}
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
you can check out from here http://php.net/manual/en/function.array-slice.php
try this, use nested for loop, this will loop 4 times. You can try to integrate with your code. If
for ($i = 0; $i < 4; $i++){
for($j = 0; $j < 4; $j++){
echo $a[$j++];
}
echo "<br/>";
}
I hope it can help you.
you can try $i++, because you use ++$i in this way "for" works 3 times!
for ($i = 0; $i < 4; $i++)

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

Store images in array PHP

I'm really new at php just doing some work, I want to save images in a php array and then show them in the screen, but I cannot save them or display them.
<?php
$min = 1;
$max = 9;
$number1 = rand($min,$max);
for ($i=1 ; $i<=$number1 ; $i++){
$firstN [$i] = echo "<img src='index.jpg' border='0'>";
}
echo $firstN [1];
?>
This is what I got , and the last line is to test it but nothing works, I google the topic but it doesn't help.
Thanks in advance.
As long as index.jpg is in the same directory as your file, this should work:
<?php
$firstN = array();
$min = 1;
$max = 9;
$number1 = rand($min, $max);
for ($i = 0; $i < $number1; $i++){
$firstN[] = '<img src="index.jpg" border="0">';
}
echo $firstN[0];
?>
Cleaned up the code a bit. When storing information in the array, you don't use echo and, like Mister pointed out, you had a space in the echo at the bottom of the code between the array-variable and the brackets.

Stuck with the number pattern printing in PHP

Stuck with the number pattern printing logic. Let me know what i am doing wrong as my file is simply going on execution without giving me a pattern.
My Code --
<?php
$num = 4;
for( $j=1 ; $j <= $num ; $j++ )
{
for( $i=$j ; $i < $num-1 ; $i++ )
{
echo " ";
}
for( $j ; $j >= 1 ; $j-- )
{
echo $j." ";
}
echo "<br />";
}
Pattern to achieve --
1
21
321
4321
UPDATE
After applying new changes following are the screenshots ---
for ($i = 1; $i <= 4; $i++) {
echo str_pad(implode('', range($i, 1)), 4, ' ', STR_PAD_LEFT) . '<br />';
}
Right aligned using CSS
echo '<div style="text-align:right;">';
for ($i = 1; $i <= 4; $i++) {
echo implode('', range($i, 1)) . '<br />';
}
echo '</div>';
Your error is in the last for, that should not exist since you are already looping.
And create a new variable which will hold the printed text for the next increment.
<?php
$num = 4;
$wrap = '';
for( $j=1 ; $j <= $num ; $j++ )
{
for( $i=$j ; $i < $num ; $i++ )
{
echo " ";
}
echo $wrap = $j.$wrap;
echo "<br />";
}
?>
The fundamental reason is that a browser wont render multiple spaces only the first one, you can overcome this by using the non breaking space html entity &nbsp in place of spaces.
Soooo, If you want your actual pattern to look like:
1
21
321
4321
And not like:
1
21
321
4321
Use &nbsp (Edit: Tho actually use [space] as just 1 seems to not compensate for the width of the 1 char vs 4)
<?php
$num = 4;
$result = array();
foreach(range($num,1) as $i){
$result[] = str_repeat(' ',$num-$i).implode('',range($i,1)).'<br />';
}
echo implode('',array_reverse($result));
?>
Or you could use a <pre> tag like:
<?php
$num = 4;
$result = array();
foreach(range($num,1) as $i){
$result[] = str_repeat(' ',$num-$i).implode('',range($i,1)).PHP_EOL;
}
echo '<pre>'.implode('',array_reverse($result)).'</pre>';
?>
As it is right now, the problem lies in your third (or second nested) for loop.
You can't just reuse $j as a counter here, since $j is still being actively used in the encompassing for loop. Substitute that for loop with:
for( $k = $j ; $k >= 1 ; $k-- )
{
echo $k." ";
}
Here is the code for your program, You can go to Develepor hell for more such pattern
// Outer look for line change
for ($i = 1; $i<=5; $i++) {
// Loop added for spacing
for ($s = $i; $s<=10-$i; $s++) {
echo " ";
}
// Inner loop for printing required pattern
for ($j = $i; $j>=1; $j--) {
echo $j;
}
echo '</br>';
}
// Here is the code for your program,
// Pattern - 1
$num = 4;
// to print no. of rows
for( $i=1 ; $i <= $num ; $i++ )
{
// To print white space
for( $j=1 ; $j <= $num-$i ; $j++ )
{
echo "0";
}
// To print pattern
for( $z= $i ; $z>=1 ; $z-- )
{
echo $z;
}
// To print new line
echo "<br />";
}
==>> Output
0001
0021
0321
4321
//===================================================================//
Pattern - 2
$z=1;
$n=3;
# no of rows
for($i=1;$i<=$n;$i++)
{
# to check even or odd
if($i%2 == 0)
{
# main logic to display in reverse order // right to left
$z = ($z+$n) -1;
$a = $z;
for($j=1;$j<=$n;$j++)
{
echo $z--;
}
$z = $a+1;
}
else
{
# display data left to right
for($j=1;$j<=$n;$j++)
{
echo $z++;
}
}
echo "<br/>";
}
==>> Output
123
654
789
Your issue appears to be that you are printing your output into an HTML document which condenses multiple spaces as its default behavior. See "Why does HTML require that multiple spaces show up as a single space in the browser?" To "preserve" whitespaces while printing, use the <pre> tag.
I'll add a math-based solution instead of multiple iterated function calls and multiple loops (inspired by my explained answer here). Once your number limit gets higher than 9, I don't know if my output will align with your desired output.
Effectively, I use printf() to left-pad every line with spaces to the same max length. Each successive number prints the integer as many times as its value.
Code: (Demo)
$num = 4;
echo "<pre>";
for ($i = 1; $i <= $num; ++$i) {
printf("% {$num}d<br>", (10 ** $i - 1) / 9 * $i);
}
HTML Output (click on the eye icon in the demo link to switch to HTML mode):
1
22
333
4444
For comparison these also work inside of the for() loop (and offer a more intuitive result above 9):
printf("% {$num}d<br>", str_repeat($i, $i));
Or
echo str_repeat(' ', $num - $i) . str_repeat($i, $i) . "<br>";

PHP - display 'X' items from foreach loop with link to display next 'X' items

I have a foreach loop which loops through an array (simpleXML nodes). This array can have between 0 and several hundred items in it. I'd like to find a way to display the first 10 results and then have a link to display the next 10 and so on.
for instance, I currently have:
$i=0;
$limit=10;
foreach ($nodes as $node){
echo "here is the output: ".$node."<br>\n";
if (++$i >=$limit) break;
}
obviously, no matter how many items are in the $nodes array, it only displays the first 10. But I think I read that foreach loops reset the counter every time they run - so if I wanted to have a link that said: next 10 itmes - I'm not sure how I would tell the the loop to start on index=10.
Am I even barking up the right tree here?
This is called pagination. You could extract the segment of the array that you need with array_slice: http://php.net/array_slice
<?php
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
$elementsPerPage = 10;
$elements = array_slice($nodes, $page * $elementsPerPage, $elementsPerPage);
foreach($elements as $node)
{
echo "Here is the output: ".$node."<br>\n";
}
Then you only need a link that points to the same page with the argument ?page=$page+1
Well, you could use a LimitIterator...
$offset = (int) (isset($_GET['offset']) ? $_GET['offset'] : 0);
$limit = 10;
$arrayIterator = new ArrayIterator($nodes);
$limitIterator = new LimitIterator($arrayIterator, $offset, $limit);
$n = 0;
foreach ($limitIterator as $node) {
$n++;
//Display $node;
}
if ($n == 10) {
echo 'Next';
}
You should use a regular for loop
if(count($nodes) < 10) {
$nnodes = count($nodes);
} else {
$nnodes = 10;
}
for($i = 0; $i < $nnodes; $i++) {
echo $nodes[$i];
}
I had the same problem, solved this way
<?php $i=0 ?>
<?php foreach ($nodes as $node) : ?>
<?php $i++ ?>
<?php echo "here is the output: ".$node."<br>\n"; ?>
<?php if ($i == 3) break; ?>
<?php endforeach; ?>
if ($n++ <= 9) {
echo 'what ever you like to get going';
}

Categories