0
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.

John AJ
  • 21
  • 1
  • 7
  • Is `$info["First_Names"]` actually an array? And you keep saying "array", singular, but surely each of `$info['First_Names']`, `$info['Last_Names']` and `$info['Gender']` are individual arrays? – user229044 Nov 04 '13 at 04:22
  • To put what meagar said in a different way, are you trying to put these values into `$info` or a two dimensional array like `$info['First_Names']`? – Machavity Nov 04 '13 at 04:30
  • Sorry, forgot to mention; Info is an array,first/lastnames and gender are all arrays in info, multidemensional array – John AJ Nov 04 '13 at 04:37

3 Answers3

1

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)
Uours
  • 2,517
  • 1
  • 16
  • 21
0

From the manual:

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;

?>
scrowler
  • 24,273
  • 9
  • 60
  • 92
0

Alternative is use a function.

<?php
function add_in_key_array($array, $key, $value){
 $array[$key][] = $value;
}
?>
Avedon
  • 1