'array_push is replacing the variables instead of adding them to the end
array_push($info["First_Names"], "$fname");
array_push($info["Last_Names"], "$lname");
array_push($info["Gender"], "$gender");
Does anyone see an issue? Array push is just replacing variables instead of adding them. The variables of $fname, $lname, and $gender are defined by the user in a form. I want the variables to simply be added to the end of the array instead of being replaced. Any responses are appreciated.
Solution 1:[1]
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
e.g.
<?php
$info["First_Names"][] = $fname;
$info["Last_Names"][] = $lname;
$info["Gender"][] = $gender;
?>
Solution 2:[2]
Alternative is use a function.
<?php
function add_in_key_array($array, $key, $value){
$array[$key][] = $value;
}
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | scrowler |
| Solution 2 | Avedon |
