Nice HTML Formatting in PHP for-loop Output - php

I'm pretty sure I found no answer here or elsewhere or maybe because it's my fault not being able to ask the right question, but anyway, say I have a for-loop in my PHP that goes something like this:
for($i=0; $i<3; $i++){
echo "$i | ";
}
How do I make the last call for " | " to not appear in order to have a nicely output:
0 | 1 | 2
INSTEAD OF
0 | 1 | 2 | <-- remove this! :(
You guys are fabulous! Thanks!!!
What if $i < $undefinedNumber ?

Keep the flow, you only need that if it's not the first:
for ($i = 0; $i < 3; $i++) {
echo $i ? " | " : '', "$i";
}
And for the first $i is 0 which means it's false. Otherwise $i is a positive integer, which means true.
Sometimes finding an alternative way to describe the problem helps to formulate a simpler answer. Instead of:
0 | 1 | 2 | /* <-- remove this! :( */
It's that problem:
/* :( remove this! --> */ | 0 | 1 | 2
The same form of solution works for CSS, too:
a:not(:first-child):before {content: ' | '}
sometimes that's easier to integrate than fiddling with PHP and HTML (Example) - however that adds the | to the link-text or style (at least in chrome where I tested it, looks buggy).

for($i=0; $i<3; $i++){
echo "$i"
if ($i != 2) {
echo " | ";
}
}
or
echo "0";
for($i=1; $i<3; $i++){
echo " | $i"
}

for($i=0; $i<3; $i++) {
if ($i == 0) {
echo "$i;
}
else {
echo " | $i"
}
}

So you just need to remove the last bar from the output? Why not skip it as you loop? Something like this:
for($i=0; $i<3; $i++)
{
echo "$i";
if($i < 2)
echo "|";
}
This would ensure that the bar only shows after the first two links, and not after the third.

$output=array();
for($i=0; $i<3; $i++){
$output[]="$i";
}
$ouput=implode(' | ', $ouput);

You can also do this:
for($i=0; $i<3; $i++) {
$arr[] = "$i";
}
echo implode(' | ',$arr);

This is a commonly found situation in programming known as the Special Case pattern. There is no built in way of solving this other than using an if statement or the ternary operator
for($i=0; $i<3; $i++){
echo "$i" . ($i != 2) ? " | " : "";

Don't do it in the php, do it in the stylesheet.
First build your HTML
<ul class="navlinks">
<?php foreach($links as $linkName => $linkUrl): ?>
<li><?php echo $linkName; ?></li>
<?php endforeach; ?>
</ul>
Apply the CSS.
.navlinks > li:after
{
content:"<li>|</li>";
}
.navlinks > li:last-child:after
{
content:"";
}
You should never style your HTML in php, this is the correct wayt to do it.

$arr = array();
for ($i=0; i<3; i++)
$arr[] = "<a href=''>$i</a>";
echo implode(" | ",$arr);
More compact version:
echo implode(" | ", array_map(function($x){return "<a href=''>$x</a>";},range(1,3)));

Related

Is my second for loop able to iterate using the increment from my first loop?

What I want is the first loop iterating from 1 to 4 and the second loop from 5 to 6.
Here is my code:
<?php
for ($i = 1 ; $i <= 4 ; $i++)
{
echo $i . "<br>";
}
?>
<hr>
<?php
for ($i = 1 ; $i <= 2 ; $i++)
{
echo $i . "<br>";
}
?>
The loops you've given are:
1st loop: from 1 to 4
2nd loop: from 1 to 2
First loop is ok, but seconds needs to be modified. Use $i<=6 and don't initialize $i variable.
This will give you:
1st loop: from 1 to 4
2nd loop: from (value that 1st loop have ended)+1 to 6, so (4+1) to 6, 5 to 6
<?php
$i = 0; // be sure 'i' is visible in both loops
for ($i=1; $i<=4; $i++) // form 1 to 4
{
echo $i . "<br>";
}
?>
<hr>
<?php
$i++; // start from 5, not 4
for (; $i<=6; $i++) // from the previous value to 6
{
echo $i . "<br>";
}
?>
Your problem
The second for loop resets your $i variable to 1:
for ($i = 1 ; $i <= 2 ; $i++)
Solution
You can use a while loop instead of your second for loop:
<?php
for ($i = 1; $i <= 4; $i++)
{
echo $i . "<br>";
}
?>
<hr>
<?php
while ($i <= 6) // `<= 6` instead of `<= 2`, since we keep $1's value
{
echo $i . "<br>";
$i++;
}
?>
Rather than using two loops for this, why not just output the <hr> tag at the appropriate point within the same one? If you carry on with adding extra loops, first of all you'll run into confusing problems like this about (re-)initialising variables, and you'll also quickly end up with a lot of unnecessary duplicated code.
You can use the PHP modulo operator (%) to output the <hr> tag after every fourth element, which will both reduce the complexity and be a lot more extensible if you later add more elements:
for ($i=1; $i<=6; $i++) {
echo $i . "<br>";
if ($i % 4 === 0) {
echo "<hr>";
}
}
See https://eval.in/976102

For loop array in php

Hello Guys how can i output this array using for loop?
This code is working but it is not for loop.
$a=array('Pol','Peter');
$b=array('3.2','2.79');
$c=array('1','1.4');
$values = array($a,$b,$c);
echo '<table border="1"><tr>';
echo '<td>'.$values[0][0].'</td>';
echo '<td>'.$values[1][0].'</td>';
echo '<td>'.$values[2][0].'</td>>';
echo '<tr><tr>';
echo '<td>'.$values[0][1].'</td>';
echo '<td>'.$values[1][1].'</td>';
echo '<td>'.$values[2][1].'</td>';
echo '</tr></table>';
Output:
--------------------------------
| Pol | 3.2 | 2.79 |
| Peter | 1 | 1.4 |
--------------------------------
Help me how loop this output.
Thanks in advance
You're looking for a for loop inside of a for loop.
The <table> tags should come outside of the outer loop, and the <tr> tags should come inside of the outer loop, but outside of the inner loop. Naturally, the <td> tags should come inside both.
This would look something like:
echo '<table border="1">';
for ($j = 0; $j < $c; $j++) {
echo '<tr>';
for ($i = 0; $i < count($values); $i++) {
echo '<td>'.$values[$i][$j].'</td>';
}
echo '<tr>';
}
echo '</table>';
Hope this helps! :)

Trying to solve this php code getting error

i am trying to print 2 4 6 8 10 with spaces, but it prints 246810.
for($i = 1; $i<= 5; $i++){
echo $i * 2.' ';
}
i am getting error : "This page isn’t working"
This might help.
for($i = 1; $i<= 5; $i++){
echo ($i * 2).' ';
}
try:
for ($i = 1; $i <= 5; $i++) {
echo ($i * 2) . ' ';
}
the main reason that your code fails is that the 2 is connected with a dot .
php interprets the 2 as an invalid type as it expects a digit next to it. e.i. 2.0
separating the 2 with a space or in the example with a parenthesis (to explicitly tell the logic) will make the code work
Problem:-2.-> php interprets the 2 as an invalid type because it is expecting a digit next to it something like 2.0. when you add space that simply tell it to apply multiplication first and then add space with it.
1.Either add a space before . like below:-
<?php
for($i = 1; $i<= 5; $i++){
echo $i * 2 .' ';
}
Output:-https://eval.in/856709
2.Or put multiplication into bracket like below:-
<?php
for($i = 1; $i<= 5; $i++){
echo ($i * 2).' ';
}
Output:-https://eval.in/856710
Try this,
for($i = 1; $i<= 5; $i++){
echo ($i * 2).' ';
}

how make a loop for inside another loop for without repeat values in a bidimensional array

I have a query in my controller, in which i search data according an id, it return 2 results, then I want search some datas according with the previously result and them shows in a view. Its something like this:
first query:
$query_1 = $obj1->Searcher_Test($type);
function Searcher_Test($type)
{
$this->db->join('n_type', 'n_type.id_test = test.id_test');
$this->db->where('test.id_type', $type);
return $this->db->get('test');
}
second query:
$query_2 = $obj2->Searcher_charact($id_test);<br>
function Searcher_charact($id_test) <br>
{<br>
$this->db->join('charact', 'charact.id_test = test.id_test');<br>
$this->db->where('test.id_test', $id_test);<br>
return $this->db->get('test');<br>
}<br>
the first query give me 2 results
id_test | test |id_type
------- |------ |--------
1 | one | 1
2 | two | 1
the second query give me 3 results
id_charact | charact | id_test
1 | moduls | 1
2 | direct | 1
3 | integer| 2
I make this for loop
$contador = 0;
$list_test = array(array());
$contador_charact = 0;
$list_charact = array(array());
for ($i = 0; $i < $query_1->num_rows; $i++) {
$id_test = $query_1->row($i)->id_test;
$query_2 = $obj2->Searcher_charact($id_test);
for ($j = 0; $j < $query_2->num_rows; $j++) {
$list_charact[$contador_charact]['charact'] = $query_2->row($j)->charact;
$contador_charact ++;
}// for j
$list_test[$contador]['test'] = $query_1->row($j)->test;
$contador++;
}// for i
and in the view I make this, but it shows me all the records, including the id_test = 1 and id_test = 2
for ($i = 0; $i < $contador; $i++) {
<div class="layout-item-0">
<?php echo $list_test[$i]['test']; ?>
for ($j = 0; $j < $contador_charact; $j++) {
?>
<li>
<?php echo $list_charact[$j]['charact']?>
</li>
<?php
} //for j
</div>
} //for i
it shows something like this:
one
moduls
directs
integer
two
moduls
directs
integer
and I want that shows
one
moduls
directs
integer
two
integer
I do not know if my query its wrong, my loop for or my view. Please help, thanks in adavance.
Thanks to all of you. I find my answer, I do this in my view:
for ($i = 0; $i < $contador; $i++) {
<div class="layout-item-0">
<?php echo $list_test[$i]['test']; ?>
for ($j = 0; $j < $contador_charact; $j++) {
if ($id_test == $list_charact[$j]['id_test']) { // <--- this is what I add
?>
<li>
<?php echo $list_charact[$j]['charact']?>
</li>
<?php
}//del if
} //for j
</div>
} //for i

issue in printing dimension of numbers php

I am just a beginner in PHP. I am trying to write program to print numbers like following.
1 1
12 21
123 321
1234 4321
1234554321
I have written the following code.
<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
echo "<br />";
for($j=1; $j<=$i; $j++)
{
echo $j;
}
}
?>
The result displays the following.
1
12
123
1234
12345
I could not reverse it like
1
21
321
4321
54321
How can I do this?
The simplest, hard coded version:
<?php
$text = "1 1
12 21
123 321
1234 4321
1234554321";
echo $text;
?>
Edit
A more generic solution:
<?php
$n = 5;
$seq1 = '';
$seq2 = '';
$format1 = sprintf("%%-%su", $n); //right justified with spaces
$format2 = sprintf("%%%su", $n); //left justified with spaces
for($i=1; $i<=$n;$i++){
$seq1 .= $i;
$seq2 = strrev($seq1);
echo sprintf("$format1$format2\n", $seq1, $seq2);
};
?>
Okay. What you wrote is pretty good. There need to be several changes in order to do what you wanted though. The first problem is that you are rendering it to HTML - and HTML does not render spaces (which we'll need). Two solutions: you use for space, and make sure you use a proportional font, or you wrap everything into a <pre> tag to achieve pretty much the same thing. So, echo "<pre>"; at the start, echo "</pre>"; at the end.
Next - don't have the inner loop go to $i. Let it go to 5 every time, and print a number if $j <= $i, and a space otherwise.
Then, right next to this loop, do another one, but in reverse (starting with 5 and ending with 1), but doing the very same thing.
Viola is a musical instrument.
Here is my solution to your problem.
It isn't the best solution because it doesn't take into account that you could be using numbers higher than 9, in which case it will push the numbers out of line with each other.
But the point is that it is still the start of a solution that you could work on if needed.
You can use an array to store the numbers you want to print.
Because the numbers are in an array it means we can just use a foreach loop to make sure all of the numbers get printed.
You can use PHP's str_repeat() function to figure out how many spaces you need to put in between each string of numbers.
The below solution will only work if you use an array with the default number indicies as opposed to an associative array.
This is because it uses the $key variable in part of the calculation for the str_repeat() function.
If you would rather not use the $key variable then you should be able to figure out how to change that.
When it come to reversing the numbers they have already been stored in a string so you can just use PHP's strrev() function to take care of that and store them in another variable.
Finally you just have to print a line to the document with a line break at the end.
Note that the str_repeat() function is repeating the HTML entity.
This is because the browser will just compress normal white space down to 1 character.
Also note that I have included a style block to change the font to monospace.
This is to ensure that the numbers all line up with each other.
<style>
html, body {
font: 1em monospace;
}
</style>
<?php
$numbers = array(1, 2, 3, 4, 5);
$numbers_length = count($numbers);
$print_numbers = '';
$print_numbers_rev = '';
foreach($numbers as $key => $value) {
$spaces = str_repeat(' ', ($numbers_length - ($key + 1)) * 2);
$print_numbers .= $value;
$print_numbers_rev = strrev($print_numbers);
echo $print_numbers . $spaces . $print_numbers_rev . '<br />';
}
Edit:
Solution without array:
<style>
html, body {
font: 1em monospace;
}
</style>
<?php
$numbers = 9;
$numbers_length = $numbers + 1;
$print_numbers = '';
$print_numbers_rev = '';
for($i = 0; $i <= $numbers; ++$i) {
$spaces = str_repeat(' ', ($numbers_length - ($i + 1)) * 2);
$print_numbers .= $i;
$print_numbers_rev = strrev($print_numbers);
echo $print_numbers . $spaces . $print_numbers_rev . '<br />';
}
$n = 5;
for ($i = 1; $i <= $n; $i++) {
$counter .= $i;
$spaces = str_repeat(" ", ($n-$i)*2);
echo $counter . $spaces . strrev($counter) . "<br/>";
}
<div style="position:relative;width:100px;height:auto;text-align:right;float:left;">
<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
echo "<br />";
for($j=1; $j<=$i; $j++)
{
echo $j;
}
}
?>
</div>

Categories