foreach loop with array? - php

I have problems with my foreach loop for the $overs array. Here is my code:
$overs[result] = array(0,1,2,3,4,5,6,7);
$overs[market] = array('H6','H7','H8','H9','H10','H11','H12','H13');
foreach ($overs as $row) {
echo $row['result'].'<br/>';
echo $row['market'].'<br/>';
}
I do not get the results like...
0
H6
for the first items for example. All I get is an empty page. No errors. Thanks for your help!

Your $row becomes an array with two arrays. You can't foreach like that.
Use normal for instead:
$overs['result'] = array(0,1,2,3,4,5,6,7);
$overs['market'] = array('H6','H7','H8','H9','H10','H11','H12','H13');
for($i=0; $i<count($overs["result"]);$i++) {
echo $overs['result'][$i]."<br/>\n";
echo $overs['market'][$i]."<br/>\n";
}
https://3v4l.org/kDObN

Not sure what exactly you are looking for but try this out and see if this serves your purpose:
<?php
$a = array(0,1,2,3,4,5,6,7);
$b = array('H6','H7','H8','H9','H10','H11','H12','H13');
$c = array_combine($a, $b);
//print_r($c);
foreach($c as $k => $v){
print $k.'<br>';
print $v.'<br>';
}
?>

Rather than a foreach consider using a for loop
I assume that the arrays in each will be the same size:
<?php
//You were missing the "'" for your keys btw
$overs['result'] = array(0,1,2,3,4,5,6,7);
$overs['market'] = array('H6','H7','H8','H9','H10','H11','H12','H13');
for($i=0; $i < count($overs['result']); $i++){
echo $overs['result'][$i] . '<br>';
echo $overs['market'][$i] . '<br>';
}

Because $row is the two arrays that you would then need to loop over. But to get them one after the other as you show, you would probably need to loop one and access the other by key. Obviously this only works correctly if the arrays are the same length and have the same keys:
foreach ($overs['result'] as $key => $val) {
echo $val.'<br/>';
echo $overs['market'][$key].'<br/>';
}

I assume you mean $overs['result'] and $overs['market'] in your first two lines,
which means it should be:
$overs['result'] = array(0,1,2,3,4,5,6,7);
$overs['market'] = array('H6','H7','H8','H9','H10','H11','H12','H13');
If so, your entire foreach is identical to the following:
echo $overs['result']['result'].'<br/>';
echo $overs['result']['market'].'<br/>';
echo $overs['market']['result'].'<br/>';
echo $overs['market']['market'].'<br/>';
Everything you're echo-ing doesn't exist, which means you should get errors similar to these:
Notice: Undefined index: result in xxx.php on line xxx
Notice: Undefined index: market in xxx.php on line xxx
You should add
error_reporting(E_ALL);
at the beginning of your script.

Related

$_POST array sometimes skips numbers and IF statement ends

I can not figure out how to print all $_POST array items (ending in successive numbers) if one or more numbers do not exist. Not sure how to explain this... For example..
$i = 1;
while( isset($options['item_code'.$i]) )
{
echo $options['item_code'.$i];
$i++;
}
This code works fine as long as the numbers continue to exist in order...
item_code, item_code1, item_code2, item_code3, etc...
But once a number is removed, the if statement stops and the rest of the values are not printed. For example...
item_code, item_code1, item_code3, etc...
Will stop at "item_code1" because item_code2 does not exist.
I've tried solutions given to similar questions here on stackoverflow but they either do not work, do the same thing, or create a continuous loop.
I would appreciate any help that someone can give me here.
you are doing it in wrong way. Please update your code like this. replace $i<=4 with number of element you want to trace
$key = end(array_keys($options));
$dataa = explode('item_code',$key);
$count = $dataa[1];
$i = 1;
while( $i <= $count )
{
if(isset($options['item_code'.$i])){
echo $options['item_code'.$i];
}
$i++;
}
I guess it can be done with an array_filter and strpos functions:
<?php
$codes = array_filter($options, function ($key) {
return strpos($key, 'item_code') === 0;
}, ARRAY_FILTER_USE_KEY);
foreach ($codes as $code) {
echo $code . PHP_EOL;
}
Instead of while use foreach like
foreach($options as $option){
echo $value;
}

Passing two variables into a 'foreach' loop

I need help regarding a foreach() loop. aCan I pass two variables into one foreach loop?
For example,
foreach($specs as $name, $material as $mat)
{
echo $name;
echo $mat;
}
Here, $specs and $material are nothing but an array in which I am storing some specification and material name and want to print them one by one. I am getting the following error after running:
Parse error: syntax error, unexpected ',', expecting ')' on foreach line.
In the Beginning, was the For Loop:
$n = sizeof($name);
for ($i=0; i < $n; $i++) {
echo $name[$i];
echo $mat[$i];
}
You can not have two arrays in a foreach loop like that, but you can use array_combine to combine an array and later just print it out:
$arraye = array_combine($name, $material);
foreach ($arraye as $k=> $a) {
echo $k. ' '. $a ;
}
Output:
first 112
second 332
But if any of the names don't have material then you must have an empty/null value in it, otherwise there is no way that you can sure which material belongs to which name. So I think you should have an array like:
$name = array('amy','john','morris','rahul');
$material = array('1w','4fr',null,'ff');
Now you can just
if (count($name) == count($material)) {
for ($i=0; $i < $count($name); $i++) {
echo $name[$i];
echo $material[$i];
}
Just FYI: If you want to have multiple arrays in foreach, you can use list:
foreach ($array as list($arr1, $arr2)) {...}
Though first you need to do this: $array = array($specs,$material)
<?php
$abc = array('first','second');
$add = array('112','332');
$array = array($abc,$add);
foreach ($array as list($arr1, $arr2)) {
echo $arr1;
echo $arr2;
}
The output will be:
first
second
112
332
And still I don't think it will serve your exact purpose, because it goes through the first array and then the second array.
You can use the MultipleIterator of SPL. It's a bit verbose for this simple use case, but works well with all edge cases:
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($specs));
$iterator->attachIterator(new ArrayIterator($material));
foreach ($iterator as $current) {
$name = $current[0];
$mat = $current[1];
}
The default settings of the iterator are that it stops as soon as one of the arrays has no more elements and that you can access the current elements with a numeric key, in the order that the iterators have been attached ($current[0] and $current[1]).
Examples for the different settings can be found in the constructor documentation.
This is one of the ways to do this:
foreach ($specs as $k => $name) {
assert(isset($material[$k]));
$mat = $material[$k];
}
If you have ['foo', 'bar'] and [2 => 'mat1', 3 => 'mat2'] then this approach won't work but you can use array_values to discard keys first.
Another apprach would be (which is very close to what you wanted, in fact):
while ((list($name) = each($specs)) && (list($mat) = each($material))) {
}
This will terminate when one of them ends and will work if they are not indexed the same. However, if they are supposed to be indexed the same then perhaps the solution above is better. Hard to say in general.
Do it using a for loop...
Check it below:
<?php
$specs = array('a', 'b', 'c', 'd');
$material = array('x', 'y', 'z');
$count = count($specs) > count($material) ? count($specs) : count($material);
for ($i=0;$i<$count;$i++ )
{
if (isset($specs[$i]))
echo $specs[$i];
if (isset($material[$i]))
echo $material[$i];
}
?>
OUTPUT
axbyczd
Simply use a for loop. And inside that loop, extract values of your array:
For (I=0 to 100) {
Echo array1[i];
Echo array2[i]
}

Accessing PHP array passed through $_POST

I passed 2 arrays through $_POST and am trying to use the data in a php function. I am able to loop through each of the arrays using a foreach loop.
However, I need to loop through one of these arrays while accessing the other one in tandem (ie, on the first element in array1, I need to access the first element of array2)--so a nested foreach loop obviously doesn't help.
I have found that I cannot access the values by numerical index, however--except the first value of the array.
Any help would be greatly appreciated.
Here is the current snippet:
$count = 1;
foreach ($quantityArray as $quantity):
if($quantity < 1){
...
$order_to_item_idArray[$count]…..
}
if($quantity > 0){
...
$order_to_item_idArray[$count]…...
}
...
$count = $count + 1;
endforeach;
You will want to use something like this to achieve what you want:
$a as $key => $c
Here (as pseudo code):
$a = array('dsa','das','asf');
$b = array('aaa','eee','ggg');
foreach ($a as $key => $c)
{
echo $c . " - " .$b[$key];
}
For your code, the line would be:
foreach ($quantityArray as $key => $quantity)

I am trying to turn an array into string, php is confounding me though?

Hi I am trying to write a piece of code that will allow me to read from an array and then output the required text as string
The code in question:
$mytext = (string)$output[0];
$breakup = explode('--', $mytext);
echo "###########################################";
echo $breakup;
This is the first time I've tried doing this and I don't think implode would work.
Could someone shed some light on what I am doing wrong or help me reach an answer?
try something like this:
$myString = "bob-fred-john-sarah-claire-julie-lisa";
$ex = explode("-", $myString);
then to see whats in the $ex array you can print it out like this:
echo "<pre>";
print_r($ex);
echo "</pre>";
to access individual values of the array you use the array index like this (remember arrays start at index 0):
echo $ex[0]; //this will echo bob.
echo $ex[1]; //this will echo fred.
to echo out each part of the $ex array you use something like a foreach loop:
foreach($ex as $index => $value){
echo $value."<br>";
}
To print out the contents of the array individually you can do it this way:
$mytext = (string)$output[0];
$breakup = explode('--', $mytext);
echo "###########################################";
for ($i=0; $i<count($breakup); $i++) {
echo $breakup[$i];
}
An alternative way is with foreach:
foreach ($breakup as $value) {
echo $value;
}
As mentioned by others, print_r can be used for displaying an array in easily readable format:
print_r($breakup);
You can also use it to store a string:
$myvalue = print_r($breakup, true); //note the ,true which will return the value instead of printing it.

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