Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

adding to an array 1

Status
Not open for further replies.

jimoblak

Instructor
Oct 23, 2001
3,620
US
Here's a dumb question but I can't get this to work for some reason...

Suppose my array is:
$fruits=array(apples,oranges,bananas);

How do I add more fruits (plums, grapes, etc) to the array?
 
If you don't care about the index just do...

$fruits[] = "plums";
$fruits[] = "grapes";

etc.

-Rob
 
My problem was how I was handling this in a session (a single quote was the thorn in my side). I am adding items to a session array based on URL GET's (example: The following will work if anyone stumbles on to this thread to ask the same question...

<?php
session_start();
if (!$PHPSESSID) {
session_register('fruits');
}

if (!$_SESSION[fruits]) {
session_register('fruits');
}

if (isset($_GET[addfruit])) {
$_SESSION[fruits][]=$_GET[addfruit];
}
 
Careful with that code...


Notice specifically the third Caution box...

$_SESSION and session_register are not meant to be used together.

The new style would be more like so...

session_start();
if (!$PHPSESSID) {
$_SESSION[&quot;fruits&quot;]=array();
}

if (!isset($_SESSION[&quot;fruits&quot;])) {
$_SESSION[&quot;fruits&quot;]=array();
}

if (isset($_GET[&quot;addfruit&quot;])) {
$_SESSION[&quot;fruits&quot;][]=$_GET[&quot;addfruit&quot;];
}


Hope that helps.

-Rob
(and the convention is to use the quotes in those array indices, I believe you can do single or double... sometimes you can get away with not using them, but on upgrades or platform switches your results may go wacky)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top