I want to split the loop into two, but I can't figure it out!
I want to loop three items from the array first, and then displaying the remaining items like this,
01 Home
02 Portfolio
03 Blog
{my website logo}
04 About
05 Contact
06 Feed
This is code where I am stuck in,
<?php
$index = 0;
foreach($items as $item)
{
?>
<li>0<?php echo $index+1;?><?php echo $item['name'];?></li>
<?php
$index ++;
}
?>
Any ideas?
Thanks.
Maybe array_slice is what you are looking for?
foreach (array_slice($items, 0, 3) as $item) {
// print item
}
// display logo
foreach (array_slice($items, 2, 3) as $item) {
// print item
}
foreach ($items as $index => $item){
echo /*<li>*/;
if ($index == 2){
echo /*logo*/;
}
}
Do you need something like that?
Try removing the loop all together and using array_slice with implode()
$first_three = array_slice($items, 0, 3);
print implode("\n", $first_three);
print "LOGO";
print implode("\n", $items);
Maybe you can just create 2 for loops
<?php
for ($i=0; $i<3; $i++) {
?>
<li>0<?php echo $i+1;?><?php echo $items[$i]['name'];?></li>
<?php
}
?>
// display logo
<?php
for ($i=3; $i<count($items); $i++) {
?>
<li>0<?php echo $i+1;?><?php echo $items[$i]['name'];?></li>
<?php
}
?>
Related
Hello I am submitting a form with POST method and I want its contents to be echo'ed one by one apart from the last one. So far I am using
<?php foreach($_POST as $data){
echo $data;
}
?>
which displays the whole array of $_POST, how can I make it using common "for" loop to not echo the last item of the array? It doesnt seem to work
<?php
$length=count($_POST)-1;
for($i=0; $i<$length; $i++) {
echo $_POST[$i];
?>
<br>
<?php } ?>
I am getting 5 errors, undefined offset 0 through 4 where the echo line is present
Do the following:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $value;
}?>
<br><?php
} ?>
Your loop for just get numerical index like $_POSR[0], $_POST[1]... This just would work if in the HTML the attribute name of the input elements be numerical also, like name="0" and so on.
foreach perform loop on array independently of index, numerical or string.
Try this:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $index => $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $index . ": " . $value;
}?>
<br><?php
} ?>
ok now I get it, I didnt know the difference between associative and numeric arrays. I fixed it with an if statement
I'm getting data from a site as you can see in the code below. Is it possible to use 3 arrays in a single foreach loop?
I've tried too many code snippets, but I haven't found the solution.
This is my normal code:
<?php
$i = 0;
$url = file_get_contents("xxx");
$display = '#{"__typename":"GraphImage","id":"(.*?)","edge_media_to_caption":{"edges":\[{"node":{"text":"(.*?)"}}]},"shortcode":"(.*?)","edge_media_to_comment":{"count":(.*?)},"comments_disabled":(.*?),"taken_at_timestamp":(.*?),"dimensions":{"height":(.*?),"width":(.*?)},"display_url":"(.*?)","edge_liked_by":{"count":(.*?)},"edge_media_preview_like":{"count":(.*?)},"location":(.*?),"gating_info":(.*?),"media_preview":"(.*?)","owner":{"id":"(.*?)","username":"(.*?)"}#i';
preg_match_all($display, $url, $dop);
foreach ($dop[1] as $displayop1) {
echo $displayop1."<p>";
}
foreach ($dop[9] as $displayop2) {
echo $displayop2."<p>";
}
foreach ($dop[15] as $displayop3) {
$i++;
if($i == 2) {break;}
echo $displayop3."<p>";
}
I've tried.
<?php
foreach ($dop[1] as $displayop1) {
foreach ($dop[9] as $displayop2) {
foreach ($dop[15] as $displayop3) {
echo $displayop1 . "<p>";
echo $displayop2 . "<p>";
$i++;
if ($i == 2) {
break;
}
echo $displayop3 . "<p>";
}
}
}
?>
<?php
foreach (array_combine($dop[1], $dop[9], $dop[15]) as $dop1 => $dop2 => $dop3) {
echo $dop1.$dop2.$dop3;
}
?>
These codes didn't work.
Can someone help me do this? I searched the solution a lot, but I couldn't find any information. I didn't know exactly how to search on the internet because my English isn't very good, thank you.
Closest option I see to a single loop is 2:
for($i=1; $i < 15; $i++) {
//you can do a if statement here if you need 1 9 and 15 respectivley
foreach ($dop[$i] as $displayop) {
}
}
My Script :
<?php
$values='Product1,54,3,888888l,Product2,54,3,888888l,';
$exp_string=explode(",",$values);
$f=0;
foreach($exp_string as $exp_strings)
{
echo "".$f." - ".$exp_string[$f]." ";
if ($f%3==0)
{
print "<br><hr><br>";
}
$f++;
}
?>
With this code i want show data inside loop, the idea it´s show all information in groups the elements in each group it´s 4 elements and must show as this :
Results :
Group 1 :
Product1,54€,3,green
Group 2:
Product2,56€,12,red
The problem it´s i don´t know why, don´t show as i want, and for example show separate some elements and not in group, thank´s , regards
It looks like you are trying to combine elements of a for loop and a foreach loop.
Here is an example of each, pulled from the php manual:
For Loop
for($index = 0, $index < size($array), $index++ {
//Run Code
//retrieve elements from $array with $array[$index]
}
Foreach
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
It's hard for me to understand what your input looks like. If you post an example of $exp_strings, I could be of better assistance. But from the sound of your question, if $exp_strings is multidimensional if you need to loop through groups of items, you could try nesting one loop inside another loop like so:
$groups_of_data = array(array(...), array(...), array(...));
for($i = 0, $i < size($groups_of_data), $i++) {
$group = $i;
for($j = 0, $j < size($groups_of_data[$i]), $j++) {
// print out data related to group $i
}
}
This is really all guesswork on my part though as I can't see what your input string/array is. Can you post that? Maybe I can be of more help.
here is code i worked out. it was kind of since i did't know what object $exp_string is. if it's a string you should tokenize it, but i think it's array from database. there was another problem, with your code where it tries to output $exp_string[$f] it should be $exp_strings what changes in the loop.
my code
$exp_string=array("Product"=>54,"price"=>3,"color"=>"green");
$f=0;
foreach($exp_string as $key => $exp_strings)
{
if($f%3==0)
{
print "<br><hr><br>";
echo "Product ".$exp_strings."<br> ";
}
else if($f%3==1)
{
echo "Price ".$exp_strings."<br> ";
}
else if($f%3==2)
{
echo "Color ".$exp_strings."<br> ";
}
$f++;
}
hope it's any help, maybe not what you wanted.
$values='Product1,1,2,3,Product2,1,2,3,Product3,1,2,3';
$products = (function($values) {
$exp_string = explode(',', $values);
$products = [];
for ($i=0; $i+3<count($exp_string); $i+=4) {
$product = [
'title' => $exp_string[$i],
'price' => $exp_string[$i+1],
'color' => $exp_string[$i+2],
'num' => $exp_string[$i+3],
];
array_push($products, $product);
}
return $products;
})($values);
/* var_dump($products); */
foreach($products as $product) {
echo "{$product['title']},{$product['price']},{$product['color']},{$product['num']}<br>";
}
How can I use foreach multiple times?
<?php
$query = $db->query('SELECT tbl_stok.id_stok,
tbl_stok.id_provinsi,
tbl_stok.id_kabupaten,
tbl_stok.tanggal,
tbl_stok.mie_instan,
tbl_stok.beras,
tbl_stok.telur
FROM `tbl_stok` INNER JOIN tbl_wilayah ON tbl_stok.id_provinsi = tbl_wilayah.id_user
');
$query->fetchAll;
?>
I want to use the first foreach to show the data tables:
<?php foreach($query as $row){
echo $row['beras'];
}?>
Then I want to use the second foreach for chart:
<?php foreach($query as $row){
echo $row['telur'];
}?>
However, this foreach works only once.
You can do this:
1) save your data to an array.
foreach($query as $row){
$data[]= $row;
}
2) use your array in every loop you want as many time you want
foreach($data as $row){
echo $row['beras'];
}
foreach($data as $row){
echo $row['telur'];
}
Use foreach only once and store all values you need, like this:
<?php
$beras_array = array();
$telur_array = array();
foreach($query as $row){
$beras_array[] = $row['beras'];
$telur_array[] = $row['telur'];
}
//you can use `for` explained later instead of two `foreach`
foreach($beras_array as $b){
echo $b;
}
foreach($telur_array as $t){
echo $t;
}
//With this method you can also use only one for instead of two foreach
$limit = count($beras_array);
for($i=0; $i<$limit; $i++){
echo $beras_array[$i];
echo $telur_array[$i];
}
?>
I hope it helps
I can usually do pretty decent with basic arrays, but this one has put my head vs the wall.
I am trying to pass some information (for a menu) through a function, and return it in a formatted fashion.
My desired end result is to send some information like this. I need to be able to repeat the array until it is empty in the event that I have a number of fields
$Sort = array('imgup.jpg','imagedn.jpg','Name','imgx.jpg','imagy.jpg','Name4');
NewSortBox($Sort);
and have an end result that would return like
<div>Name <img src='imgup.jpg'><img src='imgdn.jpg'></div>
<div>Name4 <img src='imgx.jpg'><img src='imgy.jpg'></div>
I have figured out that I have to use the Array_Chunk function to break the array, but I am not able to figure out how to make it properly use the foreach or loop functions.
function NewSortBox(&$array){
$newArray = array_chunk($array, 3, false);
$i = 0;
foreach ($newArray as $inner_array) {
$i++;
echo "<div>";
while (list($key, $value) = each($inner_array)) {
echo "$key: $value";
// Here is where I am totally lost, I want to acheive something like ??
// echo "$value[1] <img src='$value[2]'><img src='$value[3]'>";
}
echo "</div>";
}
Something like this may help to get the desired result:
$newArray = array_chunk($Sort, 3, false);
foreach ($newArray as $inner_array) {
echo "<div>";
list($a, $b, $c) = $inner_array;
echo $c.":".$b.":".$a; //arrange the variables as required
echo "</div>";
}