0

I have an associative array consist of 4 records. there is 2 input fields called name and grade. i want to add these records inside the associative array like name=>grade. here is what i did but it does not work.

$grades = array("Jim"=>"A+","Pam"=>"B","Kevin"=>"Fail","Oscar"=>"A");
$name = $_POST['name'];
$grade = $_POST['grade'];
$length = count($grades);

for($i=0; $i<$length; $i++){
    $grades = array($name => $grade);       
}

echo $_POST['name'];

enter image description here

2
  • What doesn't work? Also, what's in $_POST['name'] and $_POST['grade']? What is your expected output? Now you're replacing an array 4 times and echoing something that is not your array. Commented Jun 29, 2018 at 12:48
  • Please see the picture that i post earlier. the above text box which says "query here" is responsible for showing whats inside of associative array. we provide the name of student and it show us the grade of that student....the other 2 text boxes is used to enter records like name and grade inside the associative array... it is like store and retrive from the same associative array. hope you now understand.. please solve my problem. Commented Jun 29, 2018 at 14:20

1 Answer 1

2

Why do you need the for() loop at all? There's no need to loop over the $grades array, since you're always explicitly setting a single key/value pair.

$name should be the new key, and $grade the new value, so the following should suffice:

$grades = ["Jim" => "A+", "Pam" => "B", "Kevin" => "Fail", "Oscar" => "A" ];
$name = $_POST['name'];
$grade = $_POST['grade'];

$grades[$name] = $grade;
Sign up to request clarification or add additional context in comments.

12 Comments

ah ya mofo beat me to it
Your previous answer was faulty
@ZainFarooq Sorry?
Just in case, OP is (I think? really unclear) looking to add grades, not overwrite them.
@ZainFarooq There is no need to use $i, since $grades is an associative array, not a 0-indexed one... Anyway, I'm not entirely sure why you felt the need to point out an outdated edit was faulty, since it was edited to provide an accurate answer?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.