user1092780
user1092780

Reputation: 2457

Creating an array in PHP

If I wanted to create an array in PHP with the following format, what would be the best way to approach it? Basically I want to declare the array beforehand, and then be able to add the values to person_id, name and age.

'person_id' => array('name'=>'jonah', 'age'=> 35)

Upvotes: -2

Views: 140

Answers (3)

Etienne Noël
Etienne Noël

Reputation: 6166

To the first answer @Joe, first of all, your class doesn't support encapsulation since your attributes are public. Also, for someone who doesn't know how to create an array, this concept may be a bit complicated.

For the answer, changing a bit the class provided by @Joe, PHP provide a simple way of using arrays:

If you need many rows for this array, each row has a number, if not, remove the [0] for only one entry.

$persons = array();

$persons[0]['person_id'] = 1;
$persons[0]['name'] = 'John';
$persons[0]['age'] = '27';

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

You can start with an empty array:

$arr = Array();

Then add stuff to that array:

$arr['person_id'] = Array();
$arr['person_id']['name'] = "jonah";
$arr['person_id']['age'] = 35;

Upvotes: 1

Joe
Joe

Reputation: 15802

Depending on how you want to use it, you could make a simple object:

class Person
{
    public $person_id;
    public $name;
    public $age;
}

$person = new Person; // make the object beforehand
$person->person_id = 123; // their id
$person->name = 'Joe'; // my name
$person->age = 21; // yeah, right

This is virtually identical to an array (in terms of how it's used) except for:

  • Instead of new array() you use new Person (no brackets)
  • Instead of accessing items with ['item'] you use ->item

Upvotes: 1

Related Questions