Is It Okay to Use Array[Key] in PHP

is it safe to use a email id as a key for array in php

Short answer: If it can be a string in PHP, nowadays, it can safely be used as an associate array key.

Long answer: From the PHP manual:

The key can either be an integer or a string. The value can be of any
type.

Additionally the following key casts will occur:

Strings containing valid integers will be cast to the integer type.
E.g. the key "8" will actually be stored under 8. On the other hand
"08" will not be cast, as it isn't a valid decimal integer.

Floats are
also cast to integers, which means that the fractional part will be
truncated. E.g. the key 8.7 will actually be stored under 8. Bools are
cast to integers, too, i.e. the key true will actually be stored under
1 and the key false under 0.

Null will be cast to the empty string,
i.e. the key null will actually be stored under "".

Arrays and objects
can not be used as keys. Doing so will result in a warning: Illegal
offset type.

If multiple elements in the array declaration use the
same key, only the last one will be used as all others are
overwritten.

Is it okay to use array[key] in PHP?

It is not considered as OK -- even if it will work in most cases.


Basically, when PHP sees this :

echo $array[key];

It will search for a constant, defined with define, called key -- and, if there is none, if will take the 'key' value.


But, if there is something like this earlier in your code :

define('key', 'glop');

It will not take

echo $array['key'];

anymore ; instead, it'll use the value of the key constant -- and your code will be the same as :

echo $array['glop'];


In the end, not putting quotes arround the key's name is bad for at least two reasons :

  • There is a risk that it will not do what you expect -- which is very bad

    • It might, today...
    • But what about next week / month / year ?
    • Maybe, one day, you'll define a constant with the wrong name ;-)
  • It's not good for performance :

    • it has to search for a constant, before using 'key'
    • And, as said in a comment, it generates notices (even if you disable error_reporting and display_errors, the notices/warnings/errors are still generated, even if discarded later)

So : you should not listen to that guy on this point : he is wrong : it does matter.


And if you need some "proof" that's "better" than what people can tell you on stackoverflow, you can point him to this section of the manual, as a reference : Why is $foo[bar] wrong?

Can you use a comma in a PHP array key?

Yes, they're just strings. You can have any valid string (or integer) as an array key.

PHP: Can an array have an array as a key in a key-value pair?

You're getting an illegal offset type error because array keys can only be scalar values. From the documentation on arrays:

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer.

Since self::CAT_CRON_JOBS et al. seem like they should be constants anyways, why not just define them so that their value is the description text, and then you could just specify your array like

const CAT_STATEMENT_ADMIN = "Document Administration";

public static $CATS_AND_TYPES = array(

// Statement Administration
self::CAT_STATEMENT_ADMIN => array(
self::TYPE_STATEMENTS_LOADED => "Documents Loaded",
self::TYPE_STATEMENTS_REMOVED => "Documents Removed"
),

// etc.
)

And then you could use either $CATS_AND_TYPES[self::CAT_STATEMENT_ADMIN] (within the class, of course) or $CATS_AND_TYPES['Document Administration'] to get the same array element.

Can I use an instantiated Object as an Array Key?

From the docs:

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

You could give each instance a unique ID or override __toString() such that it returns something unique and do e.g.

$array[(string) $instance] = 42;

Is it a bad practice to use spaces in PHP associative array indexes?

No, it's not. Space symbol in programming doesn't really have a special meaning. Symbols enclosed in quotes and thus forming a string can be used as associative array keys.

In fact, there are a lot of times when using such keys for associative arrays will make your code readable and handy to make changes to it.

$scores = array("John Doe" => 100, "Ivan Ivanovich" => 75.3);

What I see is you trying to use array keys as an expression, which is REALLY bad practice. Things are meant for what they meant for. Use associative keys as associative keys.

Using an Array as the Key for an Array in PHP

PHP does have a map Class: It's called SplObjectStorage. It can be accessed with exactly the same syntax as a general array is (see Example #2 on the reference).

But to use the class you will have to use the ArrayObject class instead of arrays. It is handled exactly the same way arrays are and you can construct instances from arrays (e.g. $arrayObject = new ArrayObject($array)).

If you don't want to use those classes, you can also just create a function that creates unique hash-strings for your indexes. For example:

function myHash($array){
return implode('|',$array);
}
$rowNumberByRow[myHash($array)] = $rowNumber;

You will of course have to make sure that your hashes are indeed unique, and I would strongly suggest you use the SplObjectStorage and maybe read a little bit more about the SPL classes of php.



Related Topics



Leave a reply



Submit