Reputation: 21
$info = array(
"First_Names" => "John",
"Last_Names" => "Smith",
"Gender" => "Male",
);
array_push($info["First_Names"], "$fname");
print_r ($info);
I started learning PHP through a high school class. I'm not exactly knowledgeable nor do I pay attention much, but I'm completely stuck on this;
What I'm trying to do is get the variable $fname which is defined by the user (Jack, James, Shelly, etc) to be pushed into the array First_Names which is inside the array of $info. I'm not sure where it's going wrong, but PHP is not declaring $info as an array.
I think, it states:
Warning: array_push() [function.array-push]: First argument should be an array in /home/a4938424/public_html/process.php on line 22
If I print out the array it will show up the default names and gender,and if I echo out the $fname variable it shows up properly.)
Upvotes: 0
Views: 104
Reputation: 1051
You need to declare an array inside the array. Here is an example:
<?php
$fnames = array("John","Adam");
$lnames = array("Smith","Kowalski");
$gender = array("Male","Male");
$info = array(
"First_Names" => $fnames,
"Last_Names" => $lnames,
"Gender" => $gender
);
$new_name = "New John";
array_push($info["First_Names"],$new_name);
var_dump($info);
?>
Cheers :)
Upvotes: 0
Reputation: 4913
$info['First_Names']
isn't an array. If you are trying to push the name into $info
you will need to create an array with your info and then push it (creating a multidimensional array in the process).
$a = array("First_Names" => $fname);
array_push($info, $a);
If you are trying to overwrite the information in ['First_Name']
then simply access it by it's key.
$info['First_Name'] = $fname;
Upvotes: 0
Reputation: 782158
If you want the elements of your array to be arrays, you have to declare them as such:
$info = array(
"First_Names" => array("John"),
"Last_Names" => array("Smith"),
"Gender" => array("Male"),
);
However, IMHO this is poor design. Instead of an associative array whose values are indexed arrays, invert it to an indexed array whose elements are associative arrays.
$info = array(array('First_Name' => 'John',
'Last_Name' => 'Smith',
'Gender' => 'Male')
);
This allows you to treat each person as a single element, instead of having to loop over all the sub-arrays in parallel. To add another person to the array, you do:
$info[] = array('First_Name' => $fname, 'Last_Name' => $lname, 'Gender' => $gender);
Upvotes: 1
Reputation: 324780
$info['First_Names']
is not an array, it is a string ("John"
). If you define it as an array, it might work ;)
Upvotes: 2