This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
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.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
Related
This question already has answers here:
Compare two array and get all differences
(2 answers)
Closed last year.
I want to get difference value from array and also want to compare that difference value is from which array.
First Array => Variable : $first_array
Array {607,608,609}
Second Array => Variable : $second_array
Array {607,608,609,610}
want to get output like Difference value : 610...... From Array :- $second_array
How can i get ? please help me ....
You can use array_diff()
$result=array_diff($first_array,$second_array);
print_r($result);
Try this :
$first_array=array(607,608,609);
$second_array=array(607,608,609,610);
$result=calculate_diff($second_array,$first_array);
print_r($result);
function calculate_diff($array1,$array2)
{
$diff = [];
$larger_array = $array2;
$smaller_array = $array1;
if(count($array1) > count($array2))
{
$larger_array = $array1;
$smaller_array = $array2;
}
foreach($larger_array as $ele)
{
if(!in_array($ele,$smaller_array))
{
$diff[] = $ele;
}
}
return $diff;
}
it will work
<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$result=array_diff($a,$b);
print_r($result);
?>
or else try this
<?php
$array2 = array(607,608,609);
$array1 = array(607,608,609,275);
foreach ($array1 as $value)
{
if(in_array($value, $array2))
{
$key = array_search($value, $array2);
$key1 = array_search($value, $array1);
unset($array2[$key]);
unset($array1[$key1]);
//echo "yes<br>";
}
}
$merge = array_merge($array1,$array2);
print_r($merge);
?>
Use array_diff
<?php
$a=Array(607,608,609,610);
$b=Array (607,608,609);
$res=array_diff($a,$b);
print_r($res); // output 610
?>
Try this:
$a = array(607,608,609,610);
$b = array(607,608,609);
$c = array_diff($a,$b);
print_r($c);
Try This:
$a1=array(607,608,609,610);
$a2=array(607,608,609);
$result=array_diff($a1,$a2);
print_r($result);
Output :- Array ( [3] => 610 )
Try this by merging them and then using array_diff, array_diff_assoc and array_unique.
https://3v4l.org/Z1vpe
$first = Array(607,608,609,610);
$second = Array(800,607,608,609);
$Fcount = count($first);
$arr = array_merge($first, $second);
$arrc= array_diff($arr, array_diff_assoc($arr, array_unique($arr)));
foreach ($arrc as $key => $value){
if($key < $Fcount){
echo "first array ". $value . "\n";
}else{
echo "second array " . $value . "\n";
}
}
Edited to add how to find which array the value is in. https://3v4l.org/W7rch
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue","r"=>"black");
$d = array_merge($a1,$a2);
output:array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"red","f"=>"green","g"=>"blue","r"=>"black")
$result=array_diff($d,array_intersect($a2,$a1));
print_r($result);
output:array("d"=>"yellow","r"=>"black");
I need an out put like this.Can you please help me to sort this out?
a-1,2,4
b-3
for the following code:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
for($i=0;$i<count($paynum);$i++){
$paytypes = $paytype[$i];
$paynum = $payno[$i];
}
?>
Please Help
Just use array_unique, array_map and array_keys like this:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$uniqArr = array_unique($paytype); //Get all the unique value from array
foreach ($uniqArr as $value) {
echo $value . "-" . implode(",",array_map("matchVal",array_keys($paytype,$value)))."<br/>";
}
function matchVal($x) {
global $payno;
return $payno[$x];
}
Output:
a-1,2,4
b-3
Demo
You can try this:
<?php
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$newArr = array();
for($i=0;$i<count($paytype);$i++){
if(!isset($newArr[$paytype[$i]])) {
$newArr[$paytype[$i]] = $payno[$i];
} else {
$newArr[$paytype[$i]] = $newArr[$paytype[$i]].",".$payno[$i];
}
}
print '<pre>';print_r($newArr);
?>
Output:
Array
(
[a] => 1,2,4
[b] => 3
)
Another alternative:-
Just use a simple foreach loop:-
$paytype = ['a','a','b','a'];
$payno= [1,2,3,4];
$res = [];
foreach($paytype as $k=>$v){
$res[$v] = empty($res[$v]) ? $payno[$k] : $res[$v].','.$payno[$k];
}
print '<pre>';print_r($res);
output:-
Array
(
[a] => 1,2,4
[b] => 3
)
If you want output
a-1,2,4
b-3
then add one additional foreach at the end.
foreach($res as $k=>$v){
echo "$k-$v<br>";
}
just use this code.
$paytype = array('a','a','b','a');
$payno= array(1,2,3,4);
$result = array();
for($i=0;$i<count($paytype);$i++){
$result[$paytype[$i]][] = $payno[$i];
}
$var = '';
foreach($result as $k => $v)
{
$var .= "{$k} - ". implode(",", $v) . "<br />";
}
print_r($var);
Result :
a - 1,2,4
b - 3
I tried to use a foreach loop on a multi-dimensional array, and found out that it didn't exactly worked out the way that I expected. Is there a foreach loop for multi-dimensional arrays, or another way to do this?
$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";
foreach($array as $a) {
echo $a."<br>";
}
Result:
Nothing
Needed Result:
a
b
c
You could also try this:
foreach($array[0] as $key => $value){
echo $value . "<br>":
}
$array in this code you're accessing the key of 0,0,0 so it will not print it.
$array[0] in this code you're both accessing key 0,1,2 and the values a,b and c
You need two loops. One to loop the first array, and one to loop the inner one.
foreach($array as $key) {
foreach($key as $val) {
echo $val;
}
}
Try nesting another foreach...
$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";
foreach($array as $a) {
foreach($a as $val){
echo $val."<br>";
}
}
It is because $a is still an array. If you use print_r() you will see this:
foreach($array as $a) {
print_r($a);
}
Result:
Array
(
[0] => a
[1] => b
[2] => c
)
To combat the nested array you have to run a second foreach() loop to get the values:
foreach($array as $a) {
foreach($a as $value){ // loop through second array
echo $value . "</ br>";
}
}
well since no one else has mentioned it:
<?php
$array[0][0] = "a";
$array[0][1] = "b";
$array[0][2] = "c";
echo implode('<br>',$array[0]);
http://codepad.viper-7.com/SC9PLI
I'm having some trouble understanding the coding in PHP, when it comes to multidimensional arrays and how to push.
The idea is to push a "Attribute" and a "Attribute value"
I have tried the formula below
$i = 0;
$array = array();
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[] = ($strAtt => $strVal);
The $array[] = ($strAtt => $strVal); doesnt give me much success.
I have tried array_push($array, $strAtt => $strVal) - no luck..
As an extra questions, how do I loop trough the array and print me multidimensional values ?.
NEW CODE
while ($z->name === 'RECORD')
{
$node = new SimpleXMLElement($z->readOuterXML());
$Print = FALSE;
$output = "";
$i = 0;
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[$strAtt] = $strVal;
if(($i == 6) && ($node->PROP[$i]->PVAL == $ProductLookup))
{
$Print = TRUE;
$Product = $node->PROP[$i]->PVAL;
}
$i++;
}
if($Print == TRUE) {
echo $output;
echo "Product : ".$Product."<br>";
var_dump($array);
}
//print_r($array);
$print = FALSE;
// go to next <product />
$z->next('RECORD');
}
New code added. For some reason my $array is totally empty when i dump it, although my $Output is full of text ?
It sounds like you are wanting an "associative" array and not necessarily a multi-dimensional array. For associative arrays you don't use array_push. Just do this:
$array[$strAtt] = $strVal;
Then to loop the array just do this:
foreach ($array as $key => $value) {
echo "$key = $value\n";
}
Go through array in php , you will understand how array works in php.
Besides if you want to add an element to a multidimensional array you can achieve like this :
$node = array ("key1"=> array (a,b) , "key2"=> array (c,d));
$array = array();
foreach ($node as $key=>$value) {
$array [$key] = $value;
}
This will be the resulting $array after the loop :
array (
"key1"=> array (
a,b
) ,
"key2"=>
array (c,d)
)
Hope that helps , happy coding :)
I want to add data to an array dynamically. How can I do that? Example
$arr1 = [
'aaa',
'bbb',
'ccc',
];
// How can I now add another value?
$arr2 = [
'A' => 'aaa',
'B' => 'bbb',
'C' => 'ccc',
];
// How can I now add a D?
There are quite a few ways to work with dynamic arrays in PHP.
Initialise an array:
$array = array();
Add to an array:
$array[] = "item"; // for your $arr1
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");
Remove from an array:
$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);
There are plenty more ways, these are just some examples.
$array[] = 'Hi';
pushes on top of the array.
$array['Hi'] = 'FooBar';
sets a specific index.
Let's say you have defined an empty array:
$myArr = array();
If you want to simply add an element, e.g. 'New Element to Array', write
$myArr[] = 'New Element to Array';
if you are calling the data from the database, below code will work fine
$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
while($result = mysql_fetch_object($query))
{
//adding data to the array
$myArr[] = $result->$element;
}
}
You should use method array_push to add value or array to array exists
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/** GENERATED OUTPUT
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
*/
Like this?:
$array[] = 'newItem';
In additon to directly accessing the array, there is also
array_push — Push one or more elements onto the end of array
$dynamicarray = array();
for($i=0;$i<10;$i++)
{
$dynamicarray[$i]=$i;
}
Adding array elements dynamically to an Array And adding new element
to an Array
$samplearr=array();
$count = 0;
foreach ($rslt as $row) {
$arr['feeds'][$count]['feed_id'] = $row->feed_id;
$arr['feeds'][$count]['feed_title'] = $row->feed_title;
$arr['feeds'][$count]['feed_url'] = $row->feed_url;
$arr['feeds'][$count]['cat_name'] = $this->get_catlist_details($row->feed_id);
foreach ($newelt as $cat) {
array_push($samplearr, $cat);
}
++$count;
}
$arr['categories'] = array_unique($samplearr); //,SORT_STRING
$response = array("status"=>"success","response"=>"Categories exists","result"=>$arr);
just for fun...
$array_a = array('0'=>'foo', '1'=>'bar');
$array_b = array('foo'=>'0', 'bar'=>'1');
$array_c = array_merge($array_a,$array_b);
$i = 0; $j = 0;
foreach ($array_c as $key => $value) {
if (is_numeric($key)) {$array_d[$i] = $value; $i++;}
if (is_numeric($value)) {$array_e[$j] = $key; $j++;}
}
print_r($array_d);
print_r($array_e);
Fastest way I think
$newArray = array();
for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
{
foreach($row as $key => $value)
{
$newArray[$count]{$key} = $row[$key];
}
}