Reputation: 131
I'm working with array in PHP. My question is how to access PHP array values outside the for loop.
Here is the code.
<?php
$a = array("1","2");
for($i=0;$i<count($a);$i++){
#some core functionality DB related.
$val = $row['values'];
$b = explode(',',$val);
}
print_r($b);
$fin = array_combine($a,$b);
print_r($fin);
?>
I want to combine both the array, but I'm not getting array b
. How to access the array values outside for loop?
Expected output:
Array ( [0] => 7 [1] => 6 ) // b array
Array ( [1] => 7 [2] => 6 ) // fin array
Upvotes: 0
Views: 2323
Reputation: 1563
Try appending all the results to the original array. Something like this.
<?php
$a = array("1","2");
for($i=0;$i<count($a);$i++){
#some core functionality DB related.
$val = $row['values'];
$temp_array = explode(',',$val);
for($j=0;$j<sizeof($temp_array);$j++){
array_push($a,$temp_array[$j]);
}
}
print_r($a);
?>
Upvotes: 1
Reputation: 766
If I'm not wrong you are looking for this code with above what I have discussed with you
<?php
$a = array("1","2");
$b = array();
for($i=0;$i<count($a);$i++){
#some core functionality DB related.
$b[] = $row['values'];
}
print_r($b);
$fin = array_combine($a,$b);
print_r($fin);
?>
Upvotes: 0
Reputation: 47883
I keep staring at the original process and it seems unnecessarily convoluted. Does this not do what you wish:
$a=["1","2"];
foreach($a as $k=>$v){
// I don't know if you are using $k or $v in your DB actions
// On 1st iteration, $k=0 & $v="1"; on 2nd: $k=1 & $v="2"
$fin[$v]=explode(',',$row['values']);
}
var_export($fin);
If this is wrong please let me know how it is wrong so I can better understand the question.
Upvotes: 0