Reputation: 5
I have dump problem with foreach loop... I want to display all data in foreach, example:
$data[1] = "Hello";
$data[2] = "my";
$data[3] = "World";
I use this script and work
for($i=1; $i<3; $i++){
$mydata = $data[$i];
echo $mydata; }
This is ok, no problem. But when I want to include $mydata in next script (for saving in txt), he shows only the last word, World
Why? How to include all data from variable
Upvotes: 0
Views: 1992
Reputation: 85545
You have just echo
ed $mydata
inside for loop so it will print the value as of last occurrence value as you are changing/overriding the $mydata
variable value.
Use like this:
$mydata = '';//Storing $mydata variable
for($i=1; $i<3; $i++){
$mydata .= $data[$i]; //adding up the values to $mydata
}
var_dump($mydata); //dumps all the $data value.
Upvotes: 0
Reputation: 3812
Every time you are overwriting the variable $mydata
and your are print that one so it replacing each time, you can store that into array and dump that variable after loop ended,
for($i=1; $i<3; $i++){
$mydata[] = $data[$i];
echo $data[$i];
}
echo '<pre>';
print_r($mydata)
# You can directly dump the all the variable as follow
echo implode('\n', $mydate)
# or
echo implode('\n', data)
Upvotes: 1
Reputation: 934
Try this :
$mydata = '';
for($i=1; $i<3; $i++){
$mydata .= $data[$i];
}
echo $mydata;
Upvotes: 0