Jump to content

For loop and foreach in the same line.


lilmer

Recommended Posts

<?php

 

$test_ar = array('a','b','c','d','e');

for($i=1;$i<=10;$i++){

foreach($test_ar as $count){

 

echo $i.'-'.$count.'<br>';

 

}

}

 

so the output will be.

1-a

1-b

1-c

1-d

1-e

2-a

2-b

etc. . .

 

So how can I make this an output that will generate but using this for loop and foreach?

 

1-a-b-c-d-e

2-a-b-c-d-e

3-a-b-c-d-e

etc.

 

?>

Link to comment
https://forums.phpfreaks.com/topic/274465-for-loop-and-foreach-in-the-same-line/
Share on other sites

If you're putting it in a table, put each bit of data in it's own <td> tag, for example test this:

<?php

$test_ar = array('a','b','c','d','e');

$output = "<table>";

for($i=1;$i<=10;$i++){
$output .= "<tr><td>";
$output .= $i;
$output .= "</td>";

foreach($test_ar as $count){
$output .= "<td> $count-</td>";
}
$output .= "</tr>";
}

$output .= "</table>";

?>
<html>
<head>
<style type="text/css">
table,tr,td{border: 1px solid black;}
</style>
</head>
<body>
<?php print($output); ?>


</body>
</html>

 

Regards,

 

L2c.

Again by the way how do I resolve this??

 

  Quote

 

<table>

<tr>

<?php

 

$test_ar = array('a','b','c','d','e');

for($i=1;$i<=5;$i++){

 

echo '<td>'.$i;

foreach($test_ar as $count){

 

echo ''.$count.'';

 

}

echo '-</td>';

}

?>

</tr>

 

</table>

 

The output will be:

 

1abcde- 2abcde- 3abcde- 4abcde- 5abcde- 6abcde- 7abcde- 8abcde- 9abcde- 10abcde-

 

 

How to make it like this:

 

1a - 2b - 3c - 4d -5e

is there no solution about outputting my array inside a for loop? Cause I'm using a library and I didn't try to change the output so I just made a function array and just include it inside the loop. I know I understand that everytime my foreach has a value it will generate it again and again. How can I break it to get the first letter then on the next loop it's the second letter again. . or maybe some idea for that. THanks by the way! ::)

First off, You need to be specific about what you want. Every time you ask we've given the code then you come back and say you want something different. the code I wrote for you does EXACTLY what you asked for. Ask for EXACTLY what you need, provide the code you have, and we can help. Otherwise, this is a waste of everyone's time and it's pissing me off.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.