Jump to content

[SOLVED] Can an array have more than two 'fields'?


eco

Recommended Posts

It's my fist post so I'll stat by "Hi"!  I'm new to php and programing in general, hope you'll bare with me ;)

 

Here is my question:

 

Can an array store more than one value per 'record'?

 

What I mean is can something like the following be done?

 

[...]
$myArray = array(
   "John", "Doe", "1960";
   "Frank", "Doe", "1980";
   "Paul", "Allan", "1960";
);
[...]
return $myArray;

 

The reason for this is I have a Class that needs to return an array that should contain the first name, last name and birth year of several people.

 

Can this be done and if so, where is the documentation?

 

What would you advise I do when needing to return the above to another Class?

 

Thanks for your help.

-eco

OK, but then how do I know when to go to the next 'record'?

 

I guess the array will look something like this:

 

$myArray[0]="John"
$myArray[1]="Doe"
$myArray[2]="1960"
$myArray[3]="Frank"
$myArray[4]="Doe"
$myArray[5]="1980"
...

 

So how do I do a foreach of the array so that I can assign myArray[0,3,6] to the varaible 'first name'?

foreach($myArray as $ar) {
   $fname=$ar[0];
   $lname=$ar[1];
   $birth=$ar[2];
   print "$fname, $lname, $birth\n";
}

 

That won't work.  How would you do it?

An array of arrays.

 

eg:

 

$myArray = array(array('John', 'Doe', '1960'), array('Jane', 'Doe', '1970'));

echo $myArray[0][0]; // John

 

If you're specifically using only 3 you could do a for() like..

 

for($i = 0;$i < count($array);$i+=3)
{
     $firstName = $i;
     $lastName = ++$i;
     $year = $i+2;
}

 

Where the array would look something like yours..

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.