foreach step 5 steps forward in an array - php

How can I step forward 5 steps when using foreach to output an arrays value? So In this the put will be 1, 5
$array = ("1","2","3","4","5","6","7","8","9");
foreach ($array as &$value) {
echo $value; //Where do I tell it to move 5 paces forward?
echo "<br/ >";
}
If a foreach loop cannot be used, I'm willing to use something else. I don't think "while" or "for" can be used here?

$array = array("1","2","3","4","5","6","7","8","9");
for($i=0; $i<count($array); $i+=5) {
echo $array[$i];
echo "<br/ >";
}

I would use a while loop. Just set an index outside of the loop, and add 5 to it on each iteration of the loop. When the index is larger than the length of the list, terminate the loop.
A more compact way to express these instructions is a for loop:
for ($i=0; $i<count($array); $i = $i+5)

If it is not numerically indexed
$count = -1;
foreach ($array as &$value) {
$count++;
if ($count%4 != 0) continue;
echo "$value".PHP_EOL;
}

Related

Create multiple span based on array

I have an array that looks like this:
$elm = 'a,b,c';
I need the values of the array so I use explode to get to them:
$q = explode(",",$elm);
I then would like to echo every single item into a span, so I make an array:
$arr = array();
foreach($html->find($q[0]) as $a) {
$arr[] = $a->outertext;
}
$arr2 = array();
foreach($html->find($q[1]) as $b) {
$arr2[] = $b->outertext;
}
$arr3 = array();
foreach($html->find($q[2]) as $c) {
$arr3[] = $c->outertext;
}
And then finally I output like this:
echo "<ul>";
for($i=0; $i<sizeof($arr + $arr2 + $arr3); $i++)
{
echo "<li>";
echo "<span>".$arr[$i]."</span>";
echo "<span>".$arr2[$i]."</span>";
echo "<span>".$arr3[$i]."</span>";
echo "</li>";
}
echo "</ul>";
The problem is that I have to write all the items ($q[0] + $q[1] + $q[2]) and the corresponding span (<span>".$arr[$i]."</span>) This is a problem because in reality I don't know what and how long the first array ($elm) is. Therefore I don't want to 'physically' write down all the span elements but rather create them on the fly depending on the array $elm. I tried many things but I can't figure it out.
The basic issue here is that you don't know how many elements $elm will contain. foreach is the best choice here, as it doesn't require the length of the array to loop through it.
Use a nested foreach loop to store all the outertexts in an array:
foreach (explode(",", $elm) as $elem) {
foreach ($html->find($elem) as $a) {
$arr[$elem][] = $a->outertext;
}
}
$arr[$elem][] is the important bit here. On each iteration of the outer loop, the value of $elem will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a'], $arr['b'] and $arr['c'] and add the outertext values to the respective index.
Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:
echo "<ul>";
foreach ($arr as $sub) {
echo "<li>";
foreach ($sub as $span) {
echo "<span>".$span."</span>";
}
echo "</li>";
}
echo "</ul>";

Counting elements in multidimensional array?

I'm trying to count the nested elements in a multidimensional array. At first I thought I could use COUNT_RECURSIVE, but that counts everything. So I've tried two different approaches, none of them appeal to me. Is there a better way to do it?
$count = 0;
foreach ($topics as $t) {
foreach ($t as $c) {
$count++;
}
}
echo $count;
// or
echo (count($topics, COUNT_RECURSIVE)-count($topics));
function countNested($arr) {
return (count($arr, COUNT_RECURSIVE) - count($arr));
}
I would write this code:
$count = 0;
foreach ($topics as $t) {
$count+= count($t);
}
echo $count;
//The following example will count either one-dimensional or two-dimensional arrays
$values_count = (count($values, COUNT_RECURSIVE) - count($values)?:count($values));

putting a foreach inside foreach

I'm trying to loop some array using foreach.
This is the code which demonstrates what I'm doing:
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-".$key2."-".$val2;
}
}
However, this outputs
32-0-5
32-1-3
32-2-2
32-3-1
and I want to display it like this instead
32-1-5
45-2-3
67-3-2
89-3-1
How can I solve this? Since I'm a beginner I don't know what to do.
You don't want to loop over the 2nd array, you just want to get the value at a certain position. Try it like this:
foreach($arr1 as $key => $val){
$val2 = $arr2[$key];
echo $val."-".($key+1)."-".$val2;
}
I assume you're doing a double foreach because you actually want to print 4*4 = 16 rows. I also assume that you mistyped the last row, where you have a 3 instead of a 4.
Just using ($key2+1) can be enough for you ?
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-" . ($key2+1) . "-".$val2;
}
}
Do not nest the loops;
Use one loop and print array1[i]."-".array2[i]
You can use for loop instead of foreach too:
$arr1=array(32,45,67,89);
$arr2=array(5,3,2,1);
for ($i = 0; $i < 4; $i++) {
echo $arr1[$i] . "-" . ($i+1) . "-" . $arr2[$i];
}
$i<count ($arr1) counts the number of elements in the array.
And then stop once it gets to the end.
If you have the name number of elements in each array. This would be great for you or even to create tables dynamically.
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
for ($i=0; $i<count ($arr1) ; $i++){
echo $arr1[$i] . "-" . $arr1[$i]."-". $arr2[$i] ;
}

foreach and for loop in PHP

am working on php loops and i find myself that i need to write a nested loop bur when i try to combine foreach and for loop it yield to unexpected result
Here are my codes
foreach ($district_ward as $key => $value) {
$ward_ids = array_keys($district_ward[$key]);
echo $key;
for ($x = 0; $x < count($ward_ids)-1; $x++) {
$district_village[$key]= array_merge($value[$ward_ids[$x]], $value[$ward_ids[$x+1]]);
}
}
This gives me this
347
but when i print the value of $key within the for loop, that is
foreach ($district_ward as $key => $value) {
$ward_ids = array_keys($district_ward[$key]);
for ($x = 0; $x < count($ward_ids)-1; $x++) {
echo $key;
$district_village[$key]= array_merge($value[$ward_ids[$x]], $value[$ward_ids[$x+1]]);
}
}
i get this
3
I'm just going to guess that your 2nd and 3rd array are only one entry long. The condition for the loop specifies $x < count($ward_ids) - 1. If your array only has one entry, one - 1 will make it loop 0 times. In other words, your inner loop is not executed at all.
Are you printing this to a html page? Are your keys 3, 4 and 7? They would appear as 347 if you were echoing to an html page. Try
echo "$key<br />\n";
or even
echo "<pre>".print_r($district_ward)."</pre>";
before the loop to see what the array looks like.
foreach ($district_ward as $key => $value) {
$ward_ids = array_keys($district_ward[$key]);
for ($x = 0; $x < count($ward_ids); $x++) {
echo $key;
$district_village[$key]= array_merge($value[$ward_ids[$x]], $value[$ward_ids[$x+1]]);
}
}
Should do the trick, this because you start at 0 up UNTIL the amount of $ward_ids
Let's say your $ward_ids has 1 entry, then you would have looped 0 till 0, so no loops at all,
And lets say it had 102 entries, then you would have looped 1-101, leaving 102 out since you started at 0.

How to find the foreach index?

Is it possible to find the foreach index?
in a for loop as follows:
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
$i will give you the index.
Do I have to use the for loop or is there some way to get the index in the foreach loop?
foreach($array as $key=>$value) {
// do stuff
}
$key is the index of each $array element
You can put a hack in your foreach, such as a field incremented on each run-through, which is exactly what the for loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).
A foreach will give you your index in the form of your $key value, so such a hack shouldn't be necessary.
e.g., in a foreach
$index = 0;
foreach($data as $key=>$val) {
// Use $key as an index, or...
// ... manage the index this way..
echo "Index is $index\n";
$index++;
}
It should be noted that you can call key() on any array to find the current key its on. As you can guess current() will return the current value and next() will move the array's pointer to the next element.
Owen has a good answer. If you want just the key, and you are working with an array this might also be useful.
foreach(array_keys($array) as $key) {
// do stuff
}
You can create $i outside the loop and do $i++ at the bottom of the loop.
These two loops are equivalent (bar the safety railings of course):
for ($i=0; $i<count($things); $i++) { ... }
foreach ($things as $i=>$thing) { ... }
eg
for ($i=0; $i<count($things); $i++) {
echo "Thing ".$i." is ".$things[$i];
}
foreach ($things as $i=>$thing) {
echo "Thing ".$i." is ".$thing;
}
I think best option is like same:
foreach ($lists as $key=>$value) {
echo $key+1;
}
it is easy and normally
PHP arrays have internal pointers, so try this:
foreach($array as $key => $value){
$index = current($array);
}
Works okay for me (only very preliminarily tested though).
I use ++$key instead of $key++ to start from 1. Normally it starts from 0.
#foreach ($quiz->questions as $key => $question)
<h2> Question: {{++$key}}</h2>
<p>{{$question->question}}</p>
#endforeach
Output:
Question: 1
......
Question:2
.....
.
.
.
Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as
$var = array(2,5);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
your output will be
2
5
in which case each element in the array has a knowable index, but if you then do something like the following
$var = array_push($var,10);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.
I solved this way, when I had to use the foreach index and value in the same context:
$array = array('a', 'b', 'c');
foreach ($array as $letter=>$index) {
echo $letter; //Here $letter content is the actual index
echo $array[$letter]; // echoes the array value
}//foreach
I normally do this when working with associative arrays:
foreach ($assoc_array as $key => $value) {
//do something
}
This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:
foreach ($array as $indx => $value) {
//do something
}
foreach(array_keys($array) as $key) {
// do stuff
}
I would like to add this, I used this in laravel to just index my table:
With $loop->index
I also preincrement it with ++$loop to start at 1
My Code:
#foreach($resultsPerCountry->first()->studies as $result)
<tr>
<td>{{ ++$loop->index}}</td>
</tr>
#endforeach

Categories