Reputation: 21
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.
Upvotes: 0
Views: 3030
Reputation: 1
Alternative is use a function.
<?php
function add_in_key_array($array, $key, $value){
$array[$key][] = $value;
}
?>
Upvotes: 0
Reputation: 2492
if $info["First_Names"]
,$info["Last_Names"]
,$info["Gender"]
are arrays ,I don't see any problem .
$info = array();
$info["First_Names"] = array();
$info["Last_Names"] = array();
$info["Gender"] = array();
$fname = 'Fname1';
$lname = 'Lname1';
$gender = 'M';
array_push( $info["First_Names"] ,$fname );
array_push( $info["Last_Names"] ,$lname );
array_push( $info["Gender"] ,$gender );
$fname = 'Fname2';
$lname = 'Lname2';
$gender = 'F';
array_push( $info["First_Names"] ,$fname );
array_push( $info["Last_Names"] ,$lname );
array_push( $info["Gender"] ,$gender );
var_dump( $info );
Outputs :
array (size=3)
'First_Names' =>
array (size=2)
0 => string 'Fname1' (length=6)
1 => string 'Fname2' (length=6)
'Last_Names' =>
array (size=2)
0 => string 'Lname1' (length=6)
1 => string 'Lname2' (length=6)
'Gender' =>
array (size=2)
0 => string 'M' (length=1)
1 => string 'F' (length=1)
Upvotes: 1
Reputation: 24425
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;
?>
Upvotes: 0