Home > Software engineering >  Array will only echo last output when saving to a variable PHP
Array will only echo last output when saving to a variable PHP

Time:11-30

I have the following function in my php program.

$out = "";

printArray($_POST);
function printArray($array){
    global $out;
     foreach ($array as $key => $value){
        $out = "$key: $value <br>";
    } 
}

echo $out;

Its supposed to get all my post values along with there variable names and save it all to a variable but it only echos out the last one in my list. Meanwhile if i dont save the output of the foreach to a variable...

printArray($_POST);

function printArray($array){
     foreach ($array as $key => $value){
        echo "$key: $value <br>";
    } 
}

it outputs just fine.

first_name: Test
last_name: Test
dob1:
dob2:
dob3:
current_grade:
shcool:
M_C:
type_of_session_text:
date_session_info:
(shortened for brevity) 

whats going on here?

CodePudding user response:

This is because every itteration you set $out again without keeping the previous values. You could do:

function printArray($array){
    foreach ($array as $key => $value){
        $out .= $key.": ".$value."<br>";
    } 
    return $out;
}    

With the .= you "add" more string to that variable. The technical term is 'concatenate'.

Also, global should be avoided as it is a mayor red flag of bad programming. A function should return a value, the logic that calls the function decides what to do with it. I recommend you do a little research into 'pure' functions (easy concept).

  • Related