Skip to content
Advertisement

PHP foreach not looping

I’m new in programming and just started php like two months ago. So far I seemed to understand it more and more. But now I am stumped. I have a foreach loop that won’t loop through the array I’m feeding it. I have checked the syntax and logic over and over again and can’t find the problem. I’m probably doing something stupid, but I need your help finding out what it is.

This code is part of a script to allow a logged-in user to change his personal information. I put the data from $_POST in an array and feed it (with the session_user_id) to my function wijzig_gegevens():

if (empty($_POST) === false && empty($errors) === true) {
$gegevens = array(
    'voornaam' => $_POST['voornaam'],
    'achternaam' => $_POST['achternaam'],
    'emailadres' => $_POST['emailadres']
);
wijzig_gegevens($session_gebruiker_id, $gegevens);
}

I have checked if $gegevens is actually an array and it is; when I print_r($gegevens) I get the following output (this is an associative array, right?):

Array ( [voornaam] => Marieke [achternaam] => Schut [emailadres] => mariekeschut@gmail.com )

So the information is sent to my function wijzig_gegevens(). When I make wijzig_gegevens() return $gegevens and my primary code print_r(wijzig_gegevens()), it shows the exact same array as above. So $gegevens arrives in wijzig_gegevens() and is still an array.

So then the wijzig_gegevens() should do its part. Eventually it should update the database, but for now I/m just trying to get it to produce the key/value pairs from the array. Here’s the function:

function wijzig_gegevens($gebruiker_id, $gegevens) {
    global $db;
    $gebruiker_id = (int)$gebruiker_id;
    foreach($gegevens as $key => $value) {
    return $key.$value;
    }
}

I expected the foreach to display 3 sets of key/value pairs. But for some reason it only displays the first key/value pair:

voornaamMarieke

This has been puzzling me for over a day now, so I’m hoping someone can help me find my mistake.

Advertisement

Answer

You just return first value of loop in your code .You need an array to store whole key value of foreach loop as

$array=array();// define your array
foreach($gegevens as $key => $value) {
     $array[]=$key.$value;
}
return $array;// return array

And you get your return value as

$data=wijzig_gegevens($session_gebruiker_id, $gegevens);
print_r($data);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement