473,218 Members | 1,472 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,218 software developers and data experts.

Defining array index constants or using associatve arrays

I honestly wasn't able to find an answer for this design question using
Google and Google Groups, so I apologize if it is asked too frequently :)

Anyway: Let's say I have a multidimensional array of the following kind:

$people = array(); // maps age and e-mail address to names
$people["Paul"] = array(21, "pa**@foo.bar");
$people["Linda"] = array(22, "li***@bar.foo");
$people["Max"] = array(19, "ma*@foobar.foobar");

That obviously isn't satisfying. I don't want to remember the order in
which the data is saved for each array item. That would be tedious and
error-prone, I believe:

echo $people["Max"][1]; // a magic number...

So I might want to use an associatve array for each one:

$people = array();
$people["Paul"] = array("age" => 21, "mail" => "pa**@foo.bar");
$people["Linda"] = array("age" => 22, "mail" => "li***@bar.foo");
$people["Max"] = array("age" => 19, "mail" => "ma*@foobar.foobar");

echo $people["Max"]["mail"];

Much more legible. As someone with some C++ and C background, that still
doesn't strike me as perfect, though. What if there are hundreds of
people to save? Isn't it a big waste (plus a performance hit) to put all
those identical strings ("age" and "mail") into the array?

I may as well define constants for the array indices:

define("PEOPLE_INDEX_AGE", 0);
define("PEOPLE_INDEX_MAIL", 1);

$people = array(); // maps age and e-mail address to names
$people["Paul"] = array(21, "pa**@foo.bar");
$people["Linda"] = array(22, "li***@bar.foo");
$people["Max"] = array(19, "ma*@foobar.foobar");

echo $people["Max"][PEOPLE_INDEX_MAIL];
Is there any reason not to use this solution? My C++ and C thinking
might affect my reasoning in a way that is not good for PHP programming.
Any help on this design issue would be most appreciated, as would be
links where I can learn more about such basic PHP design guidelines.
--
Christian Hackl
Jul 17 '05 #1
4 3649
I would combine your second and your third solutions:

$people["Paul"] = array(PEOPLE_INDEX_AGE => 21, PEOPLE_INDEX_MAIL =>
"p...@foo.bar");
$people["Linda"] = array(PEOPLE_INDEX_AGE => 22, PEOPLE_INDEX_MAIL =>
"l...@bar.foo");
$people["Max"] = array(PEOPLE_INDEX_AGE => 19, PEOPLE_INDEX_MAIL =>
"m...@foobar.foobar");

Or, even better IMHO, I would use classes:

class Person {
var $age;
var $address;

function Person($age, $address) {
$this->age = $age;
$this->address = $address;
}

function getAge() {
return $this->age
}

function getAddress() {
return $this->address;
}
}

$people["Paul"] = new Person(21, "p...@foo.bar");

Jul 17 '05 #2
"Christian Hackl" <ha***@sbox.tugraz.at> wrote in message
news:42***********************@newsreader01.highwa y.telekom.at...
So I might want to use an associatve array for each one:

$people = array();
$people["Paul"] = array("age" => 21, "mail" => "pa**@foo.bar");
$people["Linda"] = array("age" => 22, "mail" => "li***@bar.foo");
$people["Max"] = array("age" => 19, "mail" => "ma*@foobar.foobar");

echo $people["Max"]["mail"];

Much more legible. As someone with some C++ and C background, that still
doesn't strike me as perfect, though. What if there are hundreds of
people to save? Isn't it a big waste (plus a performance hit) to put all
those identical strings ("age" and "mail") into the array?

I may as well define constants for the array indices:

define("PEOPLE_INDEX_AGE", 0);
define("PEOPLE_INDEX_MAIL", 1);

$people = array(); // maps age and e-mail address to names
$people["Paul"] = array(21, "pa**@foo.bar");
$people["Linda"] = array(22, "li***@bar.foo");
$people["Max"] = array(19, "ma*@foobar.foobar");

echo $people["Max"][PEOPLE_INDEX_MAIL];
Is there any reason not to use this solution? My C++ and C thinking
might affect my reasoning in a way that is not good for PHP programming.
Any help on this design issue would be most appreciated, as would be
links where I can learn more about such basic PHP design guidelines.


No reason not to. You just don't gain much by going this route. PHP arrays
are very different from C arrays. They are hash tables. Even when you access
an element by a numeric index, PHP would still perform a hash look up. The
only thing you save speedwise is in the generation of the hash key. And if
you use a constant, you cough the saving back up, since the value of PHP
constants are obtained from a hash table at runtime. You do save on memory
though, since the key isn't stored multiple times in the hash table.

Objects are also implement using hash tables. There isn't a great difference
between $person->age and $person['age']. I prefer using objects for storing
data, since it makes more sense conceptually. Object properties are also
easier to interpolate into strings ("$person->age years old" vs
"{$person['age']} years old").
Jul 17 '05 #3
Chung Leong wrote:
No reason not to. You just don't gain much by going this route. PHP
arrays are very different from C arrays. They are hash tables. Even
when you access an element by a numeric index, PHP would still
perform a hash look up. The only thing you save speedwise is in
the generation of the hash key. And if you use a constant, you cough
the saving back up, since the value of PHP constants are obtained
from a hash table at runtime. You do save on memory though, since
the key isn't stored multiple times in the hash table.


Thanks for yours and Jean-Baptiste's answers. That's most interesting.
I'll probably go the arr["Index"] route then, since I am not to keen on
mixing classes into my currently purely procedural PHP code.

P.S.: Sorry for posting through Google, but my news server ate this
whole thread for reasons unknown (hence the late reply) :(

--
Christian Hackl

Jul 17 '05 #4

"Christian Hackl" <ha***@sbox.tugraz.at> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
Thanks for yours and Jean-Baptiste's answers. That's most interesting.
I'll probably go the arr["Index"] route then, since I am not to keen on
mixing classes into my currently purely procedural PHP code.


Better to go $array['index'] as single quotes prevent evaluating the string
first for interpolations like $array["index"] would.

Unless you want to do that of course!

Matt
Jul 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Pjotr Wedersteers | last post by:
Hello, I tried to create an array with 1000 cells, keys 0 thru 999 using $myarr = array (1000); But this leads to an array of 1 cell with value 1000; Now I have a workable solution for...
3
by: Roy Riddex | last post by:
I've just moved onto 2-D Arrays in my VB6 beginners book. I'm struggling to get my head around the following problem but no doubt you will think it rather easy. My program is supposed to allow up...
47
by: VK | last post by:
Or why I just did myArray = "Computers" but myArray.length is showing 0. What a hey? There is a new trend to treat arrays and hashes as they were some variations of the same thing. But they...
22
by: VK | last post by:
A while ago I proposed to update info in the group FAQ section, but I dropped the discussion using the approach "No matter what color the cat is as long as it still hounts the mice". Over the last...
16
by: herbertF | last post by:
Hi guys, In a program (not my own) I encountered the declaration of a constant pointer to an array consisting of two other const pointers to arrays. Not quite sure why they do it so complicated,...
11
by: truckaxle | last post by:
I am trying to pass a slice from a larger 2-dimensional array to a function that will work on a smaller region of the array space. The code below is a distillation of what I am trying to...
10
by: | last post by:
I'm fairly new to ASP and must admit its proving a lot more unnecessarily complicated than the other languages I know. I feel this is because there aren't many good official resources out there to...
29
by: foker | last post by:
I have this problem where I have 2 text files, one with student name, id#, # of courses and course #, the second file has course name and course number. I want to make a multidimensional array that...
6
by: lazy | last post by:
Hi, Im trying to define a hashtable thats static(meaning the table is initialised at compile time itself) It takes a char and has 2 other ints as values For eg: arr={1,2}...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.