Foreach only showing last item in array [duplicate] - php

This question already has answers here:
Array Foreach Loop Prints Last Item Only [closed]
(4 answers)
Closed 9 months ago.
I'm attempting to make a foreach loop to iterate over each item in an array, but it only captures the last item and does not iterate over the first one. I've stripped down the code to only show the relevant parts and added some commands to identify the problem as described above.
$message == "kk,ll";
$myArray = explode(',', $message);
print_r ($myArray);
foreach ($myArray as $value);
{
echo "$value <br>";
$array[] = $value;
}
print_r ($array);
The output is:
Array ( [0] => kk [1] => ll ) ll
Array ( [0] => ll )
You can see that when I use print_r() the array contains two items. But the foreach loop only loops over the last item. Adding the array elements into a new array inside the loop also ends up with an array containing only the last element. What am I doing wrong?

You have two mistakes in you code:
In your first line you have two equal signs which should only be one.
In your foreach loop, you have by mistake put an semicolon at the end:
foreach ($myArray as $value);
Doing this, the foreach loop will run, but the code inside the {} is actually placed outside the foreach loop, and thereby causing $value only to store the last element of the array.
The code should look like this:
$message = "kk,ll";
$myArray = explode(',', $message);
print_r ($myArray);
foreach ($myArray as $value) {
echo "$value <br>";
$array[] = $value;
}
print_r ($array);

your foreach just assigned the $value, but output nothing. This is caused by the ; after foreach, same as
foreach ($myArray as $value)
{}
And after this, the $value have the last element of $myArray, then
{
echo "$value <br>";
$array[] = $value;
}
only output the last element.

remove the ; after the Foreach like in the follow code
foreach ($myArray as $value)
{
echo "$value <br>";
$array[] = $value;
}

In Laravel Framework Use Code into Controller:
$dd = $categories->pluck( 'title' )->toArray();
foreach ( $dd as $key => $value ) {<br />
$array[$key] = '.' . $value;<br />
} <br />
$cat = implode( ',' , $array );
<br />
// Result Display : James,Mark,Helmet.....

Only remove the semicolon after foreach ($myArray as $value) or used it

Related

How to print PHP array values without square brackets and symbols?

I want to print an array without printing the square brackets and the word "Array", for example if I do
print_r($Array);
I will get this:
Array ( [0] => Example0 [1] => Example1)
How can I get this?
Example0
Example1
Any of these ways should work just fine.
// First way
print_r(implode("<br>", $your_array));
// Second way
for ($i = 0; $i < count($your_array); $i++) {
print_r($your_array[$i]);
echo "<br>";
}
// Third way
foreach ($your_array as $value) {
print_r($value);
echo "<br>";
}
The first method works for one-dimensional arrays only. If you have multidimensional arrays, you need to use for loops and to check whether the current element is an array or not and recursively enter into more for loops in order to print out all the data.
You can do it in this way:
function print_array ($array) {
foreach ($array as $key => $value) {
if (is_array ($value)) {
print_array ($value);
} else {
echo ($value."<br />");
}
}
}
You could use array walk recursive
$array = ['Example0','Example1', ['Example2']];
array_walk_recursive($array,function($item,$key){echo"$item\n";});
// tip use <br> instead of \n for HTML
Outputs
Example0
Example1
Example2
See it online
array_walk_recursive — Apply a user function recursively to every member of an array
So this will seamlessly handle multi-dimensional arrays, as my example shows.
If I understood correctly, you want to print the values for each key. You can use
foreach ($Array as $value) {
print_r($value);
echo "\n";
}
This will result in
Example0
Example1
foreach($Array as $key) {
echo $key.", ";
}

Is there any special rule to use foreach and while loop(using each() function) to iterate over an array in php?

I am new in PHP.
My question is that when i use following script:
$arr1 = array('fname' => 'niraj','lname' => 'kaushal','city' => 'lucknow');
while(list($key, $value) = each($arr1)){
echo "$key has $value value <br>";
}
foreach($arr1 as $key => $value){
echo "$key:$value <br>";
}
it outputs
fname has niraj value
lname has kaushal value
city has lucknow value
fname:niraj
lname:kaushal
city:lucknow
but when i change order of foreach and while loop as follow
$arr1 = array('fname' => 'niraj','lname' => 'kaushal','city' => 'lucknow');
foreach($arr1 as $key => $value){
echo "$key:$value <br>";
}
while(list($key, $value) = each($arr1)){
echo "$key has $value value <br>";
}
it gives following output
fname:niraj
lname:kaushal
city:lucknow
Why second script doesn't display the output of while loop. What the reason behind it.
It is because each() only returns the current key/value and then advances the internal counter (where in the array you are currently). It does not reset it.
The first loop (foreach) sets the internal counter to the end of the array, so the second loop thinks it is already done and therefore does nothing.
You need to call reset() on the array before starting the loop using each():
reset($arr1);
while (list($key, $value) = each($arr1)){
echo "$key has $value value <br>";
}

How to extract all 2nd level values (leaf nodes) from a 2-dimensional array and join with commas?

How can I get the list of values from my array:
[data] => Array
(
[5] => Array
(
[0] => 19
[1] => 18
[2] => 20
)
[6] => Array
(
[0] => 28
)
)
Expected output result string will be: 19,18,20,28
Thanks!
With one line, no loop.
echo implode(',', call_user_func_array('array_merge', $data));
Try it here.
Use following php code:
$temp = array();
foreach($data as $k=>$v){
if(is_array($v)){
foreach($v as $key=>$value){
$temp[] = $value;
}
}
}
echo implode(',',$temp);
Use following code.
$string = '';
foreach($yourarray as $k){
foreach($k as $l){
$string. = $l.",";
}
}
Just loop over sub arrays. Store values to $result array and then implode with ,
$result = array();
foreach ($data as $subArray) {
foreach ($subArray as $value) {
$result[] = $value;
}
}
echo implode(',', $result);
$data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
foreach ($array as $array1) {
echo $array1.'<br>';
}
}
Try this one. It will help you
Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});
Output:
19,18,20,28
This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)
I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array. It's a tidy little one-liner with a bit of regex magic. (Regex Demo) It effectively removes all square & curly brackets and double-quoted keys with trailing colons.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));
Output:
19,18,20,28
To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.
try with this..
foreach($data as $dataArr){
foreach ($subArray as $value) {
$res[] = $value;
}
}
echo implode(',', $res);
Just use nested foreach Statements
$values = array();
foreach($dataArray as $key => $subDataArray) {
foreach($subDataArray as $value) {
$values[] = $value;
}
}
$valueString = implode(',', $values);
Edit: Added full solution..

String to an array and then foreach

I have a variable string which is passed to an and array then foreach that just does not want to work. Below is the code im using.
$explode = $_obj->getModDependencies();
//this variable will returns/echos the string as #ModA,#Mod_b,#Mod3 etc (yes # is in each value)
and the foreach and array php code im using
$arr = array($explode);
foreach ($arr as $value) {
echo ''.$value.'';
}
if i use the above code it echos one hyperlink with each value at the end of it (http://myurl/mod?mod_id=#ModA,#Mod_b,#Mod3) but i want to echo each hyperlink for each value.
Which would be
http://myurl/mod?mod_id=#ModA
http://myurl/mod?mod_id=#Mod_b
and so forth.
But if i place the actual variable output string directly into the array it echos out how i want it (see below code that works)
$arr = array(#ModA,#Mod_b,#Mod3);
foreach ($arr as $value) {
echo ''.$value.'';
}
Any help wold be awesome!!
$arr = array($explode);
Thats the issue, just by saying something is within array() doesnt really make it an array as you expect it to be. You only gave it 1 argument.
You also mentioned the value of $explode is like this #ModA,#Mod_b,#Mod3. Just by naming something $explode doesn't explode it. You have to explode it yourself
$arr=explode(",","#ModA,#Mod_b,#Mod3");
//$arr=explode(",",$explode) in your case
Once that is done, your loop is already fine
foreach ($arr as $value) {
echo ''.$value.'';
}
Fiddle
When your variable $explode will be a string as '#ModA,#Mod_b,#Mod3' then you have to explode it.
$arr = explode(',', $explode);
foreach ($arr as $value) {
echo ''.$value.'';
}

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Categories