Named vs Numeric Array Indexes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Named vs Numeric Array Indexes

Post by VladSun »

Weirdan wrote:
VladSun wrote:it's even without E_NOTICE raised ;) )
What's with E_NOTICE?
My fault - I should have explained myself better. Iwas talking about:

Code: Select all

if ($config[someFeature][enabled]) {
   // do something
}
no define()s, E_NOTICE (or E_WARNING, not sure) raised, but still working (exactly the same as yours, but no qutoes ;) ) :)


I was just playing the devil's advocate - just to show the other side of the story ;)
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Named vs Numeric Array Indexes

Post by Weirdan »

Still, less special characters which, at least for me, is faster to code.
Less characters to type in config would likely cause more characters to type elsewhere, because with disparate variables you lose the ability to operate on entire sections of config. Consider this example:

Code: Select all

// config.php
return array(
     'features' => array(
         'registration' => array(
              'enabled' => true,
              'required' => true,
              'notifyAdmin' => true,
         ),
         'comments' => array(
              'enabled' => true,
              'show' => 'threaded', // could be also 'plain'
              'perPage' => 10,
              'showAvatars' => true,
         ),
     ),
);

Code: Select all

$config = include "config.php";
//......

showComments($data, $config['features']['comments']);


function showComments($data, $config) 
{
    if (!$config['enabled']) return;
    if($config['type'] == 'threaded') {
         // show threaded comments, limiting number of threads per page to $config['perPage']
         // show avatars depending on $config['showAvatars']
    } else {
         // show plain comments, limiting number of comments per page to $config['perPage']
         // show avatars depending on $config['showAvatars']
    }
}
To pass the all relevant configuration to showComments() function you'd have to pass 4 variables (with quite long names), as opposed to one.
User avatar
ColonelSandersLite
Forum Commoner
Posts: 35
Joined: Sun May 09, 2010 1:32 am

Re: Named vs Numeric Array Indexes

Post by ColonelSandersLite »

Weirdan wrote:To pass the all relevant configuration to showComments() function you'd have to pass 4 variables (with quite long names), as opposed to one.
Why would you need to pass the config values into the function, instead of just including from the function if you need them in the first place?

Code: Select all

// config.php
$cfg_registration_enabled     = true;
$cfg_registration_required    = true;
$cfg_registration_notifyAdmin = true;

$cfg_comments_enabled     = true;
$cfg_comments_show        = 'threaded'; // could be also 'plain'
$cfg_comments_perPage     = 10;
$cfg_comments_showAvatars = true;

Code: Select all

include "config.php";
//......

showComments($data);


function showComments($data) 
{
    include "config.php";
    if (!$cfg_comments_enabled) return;
    if($cfg_comments_show == 'threaded') {
         // show threaded comments, limiting number of threads per page to $config['perPage']
         // show avatars depending on $config['showAvatars']
    } else {
         // show plain comments, limiting number of comments per page to $config['perPage']
         // show avatars depending on $config['showAvatars']
    }
}
Not several extra lines of code. IMHO, this is faster to type in the first place and easier to read. You could also have used $GLOBALS to do the job as well. Besides which, If you ask me, using arrays inside of a config file which you expect may be editited by an end user is a *bad idea*.


Aside: you also have a bug in your code (referencing a non-existant variable). Line 10 of the second code box should be: if($config['show'] == 'threaded') {
Sephern
Forum Commoner
Posts: 73
Joined: Sun Jan 04, 2009 4:44 pm

Re: Named vs Numeric Array Indexes

Post by Sephern »

Named arrays are pretty useful if you expect someone else to be modifying, maintaining or adding on to your code.

Using the example of vBulletin (which I've been coding for a bit recently), you reference arrays like this

$bbuserinfo['username']
$bbuserinfo['userid']
etc

If you were to try and do that with numeric arrays the learning curve would be insanely steep. Though I tend to use the Object Orientated alternatives the majority of the time.

Another example where I've found Named indexes to be more useful of late is where I've got, say, a shopping cart. Each record has a numeric index for the key (its id in the database), and then a named array for the value (Product name, Product Quantity, Product Price, etc). That way their array of products can be saved in the session as one variable.

Generally having named array indexes is syntactic sugar, and makes it easier to understand your code. If you don't like them, then don't use them.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Named vs Numeric Array Indexes

Post by Weirdan »

ColonelSandersLite wrote: Why would you need to pass the config values into the function, instead of just including from the function if you need them in the first place?
And do that several times, increasing both run time and memory consumption? Not an option.
User avatar
ColonelSandersLite
Forum Commoner
Posts: 35
Joined: Sun May 09, 2010 1:32 am

Re: Named vs Numeric Array Indexes

Post by ColonelSandersLite »

It's a better option than expecting an end user to understand arrays. If the additional millisecond loadtime an issue, use global. If for some reason you don't want to do that, than VladSun's constants are genuinely better. As far as memory goes, you're aware that memory is *cheap*? At $20-$30 per gig, quite frankly, you can reasonably supply any memory consumption a php program will use for next to nothing on all but the busiest of servers. Hell, once you start talking about servers that busy, it's cheaper to throw more memory at it than pay a programmer to search for and implement code optimizations. Especially if it's an engineer who has enough experience and knows his stuff well enough to actually make a significant impact.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Named vs Numeric Array Indexes

Post by Weirdan »

ColonelSandersLite wrote:As far as memory goes, you're aware that memory is *cheap*?
That's popular misconception that only holds true in desktop and low-load server market (and even there nowadays you get pretty limited memory). Once you get to even moderate load (in order of several millions hits per day) memory starts being the most precious resource. And at any time you have only so much, and there are always better uses for it other than wasting it just because you don't like some part of php syntax.
ColonelSandersLite wrote:At $20-$30 per gig, quite frankly, you can reasonably supply any memory consumption a php program will use for next to nothing on all but the busiest of servers.
No, you're limited by what amount of memory you can stuff into the motherboard. And, unless you're running your own servers, adding memory is not a one-time spending - it increases your monthly server bill.
ColonelSandersLite wrote:Hell, once you start talking about servers that busy, it's cheaper to throw more memory at it than pay a programmer to search for and implement code optimizations.
We weren't talking about optimizations, that's how many people approach such task from the start.


You see, you asked why people use associative arrays. You've been given your answer: 9 times of 10 they use it for readability. $row['userid'] is more readable than $row[7]. After that it quickly deteriorated to 'is there any way to not use it?'. Yes, there are ways, all of them with their own shortcomings making them questionable to pursue.

Now ask yourself what you're doing now in this thread? Trying to convince us to not use associative arrays? That's not gonna happen, especially since you haven't offered any compelling reasons aside from 'they are more characters to type'. Trying to justify not changing anything in the way you code? That's hardly a valuable goal, and you don't have to do it publicly.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Named vs Numeric Array Indexes

Post by VladSun »

I tend to use "strict mode" when using associative arrays for object configuration. E.g.:

Code: Select all

class ModuleConfig
{
	protected $package		= '';
	protected $name			= '';

	protected $standalone	= false;
	protected $clientSide	= true;

	protected $hooks		= null;
	protected $classes		= null;

	public function  __construct($config)
	{
		foreach ($config as $property => $value)
		{
			if (property_exists($this, $property))
				$this->{$property} = $value;
			else
				throw new ModuleConfigException("Property {$property} doesn't exist.");
		}
	}

	public function __call($method, $args)
	{
		if (substr($method, 0, 3) == 'get')
		{
			$property = substr($method, 3);
			$property{0} = strtolower($property{0});

			if (property_exists($this, $property))
				return $this->{$property};
			else
				throw new ModuleConfigException("Property {$property} doesn't exist.");
		}
	}
}

class ModuleConfigException extends Exception {};
This way I ensure there are no configuration item name mistakes.
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply