Skip to content
Advertisement

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.

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement