Ganesh Lalam
Ganesh Lalam

Reputation: 1

How to write foreach loop for array in php

After submitting the form i am getting the array

$regData = {"student":"699","eposter":"99","exhibitor":"1199","Single-2-nights":"400"};

I need this look like this:

student : 699  
eposter : 99  
exhibitor : 1199  
Single-2-nights : 400  

I am writing this like:

<?php
foreach($regData as $key => $value){  
    $selected .= $key." :". $value."<br/>";  
}  
?>

Showing error

invalid argument passed to forech

Please help me to fix this error

Upvotes: 0

Views: 82

Answers (4)

JPA
JPA

Reputation: 174

It is a JSON String, You have to decode it first using Json_decode

    $regData = '{"student":"699","eposter":"99","exhibitor":"1199","Single-2-nights":"400"}';
    $arrayData = json_decode($regData,true);
    $selected ='';
    foreach($arrayData as $key => $value){
    $selected .= $key." :". $value."<br/>";
    }

Upvotes: 3

dragos.nicolae
dragos.nicolae

Reputation: 78

$regData = '{"student":"699","eposter":"99","exhibitor":"1199","Single-2-nights":"400"}';
print_r(json_decode($regData));

will result an object

Upvotes: 2

Umair Malik
Umair Malik

Reputation: 35

Hi Ganesh I Checked your code, your foreach loop syntax is fine but It's a better practice to write endforeach; at the end of loop + in your array replace : with =>

Upvotes: 0

Naveed Ramzan
Naveed Ramzan

Reputation: 3593

$regData = ["student" => "699",
            "eposter" => "99",
            "exhibitor" => "1199",
            "Single-2-nights" => "400"];

in php, array should be in square brackets

foreach($regData as $key => $value){  
    $selected .= $key." :". $value."<br/>";  
}

Foreach code is OK.

?>

Upvotes: 1

Related Questions