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] ;
}
Related
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;
}
Hopefully this is a simple answer or doable in some other way. I want to use parse_str to store my querystring values in an array.
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
Accessing the data by name works correctly:
echo $fields['value3'];
... but accessing via index does not:
echo $fields[2];
The reason I want to access by index instead of name is because after the 2nd array value, the rest of the querystring parameters will be DYNAMICALLY generated. In other words, for the processing I'm doing -- I want to get all parameters AFTER the 2nd one. To do that, I was going to use a simple FOR loop starting from the 3rd value in the array to the sizeof(myArray);.
Any ideas how I can accomplish this?
You have to generate an indexed array then. You could for example use:
$indexed = array_values($fields);
print $indexed[2]; // eqivalent to $fields["value3"];
Note that the index starts from 0.
If you want you could also combine the named array with the indexed version:
$fields = array_merge($fields, array_values($fields));
$fields[2] == $fields["value3"];
$i = 0;
foreach ($fields as $key => $value) {
$fields[$i] = $value; //or just put your code here, and use $i
$i++;
}
for ($j = 2; $j < $i; $j++) {
//do something with $fields[$j]
}
Here:
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
$arr = array_slice($fields, 2, count($fields), true);
foreach($arr as $key=>$value) {
echo $key . "=>" . $value;
}
Just concatenate a string with an integer:
echo $fields["value" . $myInteger + 1];
where myInteger is your value (for loop, etc.). You need to add 1 because your strings are one-based.
Example:
for ($i = 2; $i < sizeof($myArray); $i++)
{
echo $fields["value" . $i + 1];
}
Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");
i want to have a foreach loop where the initial array is changed inside the loop.
eg.
$array = array('red', 'blue');
foreach($array as $key => $value) {
$array[] = 'white';
echo $value . '<br />';
}
in this loop the loop will print out red and blue although i add another element inside the loop.
is there any way to change the initial array inside the loop so new elements will be added and the foreach will use the new array whatever is changed?
i need this kind of logic for a specific task:
i will have a if statement that search for a link. if that link exists, it is added to the array. the link content will be fetched to be examined if it contains another link. if so, this link is added, and the content will be fetched, so on so forth.. when no link is further founded, the foreach loop will exit
I don't think this is possible with a foreach loop, at least the way you wrote it : doesn't seem to just be the way foreach works ; quoting the manual page of foreach :
Note: Unless the array is referenced, foreach operates on a copy
of the specified array and not the
array itself.
Edit : after thinking a bit about that note, it is actually possible, and here's the solution :
The note says "Unless the array is referenced" ; which means this portion of code should work :
$i = 0;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
}
Note the & before $value.
And it actually displays :
red
blue
white
white
white
white
Which means adding that & is actually the solution you were looking for, to modify the array from inside the foreach loop ;-)
Edit : and here is the solution I proposed before thinking about that note :
You could do that using a while loop, doing a bit more work "by hand" ; for instance :
$i = 0;
$array = array('red', 'blue');
$value = reset($array);
while ($value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
$value = next($array);
}
Will get you this output :
red
blue
white
white
white
white
What you need to do is move the assignment inside the for loop and check the length of the array every iteration.
$array = array('red', 'blue');
for($i = 0; $i < count($array); $i++)
{
$value = $array[$i];
array_push($array, 'white');
echo $value . '<br />';
}
Be careful, this will cause an infinite loop (white will be added to the end of the array at every loop).
Maybe you should use some other way, like:
$ar = array('blue', 'red');
while ($a = array_pop($ar) {
array_push($ar, 'white');
}
Or something like this...
You can access the array by using the $key
$array = array('red', 'blue');
foreach($array as $key => $value) {
$array[$key] = 'white';
}
In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by
reference. [source]
All you have to do to your old code is
precede $value with &
like so
$array = array('red', 'blue');
foreach($array as $key => &$value) {// <-- here
$array[] = 'white';
echo $value . '<br />';
}
A while loop would be a better solution.
while (list ($key, $value) = each ($array) ) {
$array[] = 'white';
echo $value . '<br />';
}
If you don't need the $key variable, as your example suggests then using $value = array_pop($array) instead if list ($key, $value) = each ($array) would be a less expensive option. see #enrico-carlesso's Answer Here
As your array is sequantial(numeric,indexed) and not associative then you could use a for loop instead.
for ($key = 0; $key < count($array); ++$key) {
$value = $array[$i];
$array[] = 'white';
echo $value . '<br />';
}
As a side note.
I don't understand why its &$value and not &array.
&$value would suggest you can only modify the current element within the loop.
&array would suggest you could modify all array elements within the loop, including adding/removing element.
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