Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Hypens, Underscore or camelCase in php arrays?

Tags:

arrays

php

I just started using php arrays (and php in general)

I have a code like the following:

languages.php:

<?php
$lang = array(
    "tagline" => "I build websites...",
    "get-in-touch" => "Get in Touch!",
    "about-h2" => "About me"
    "about-hp" => "Hi! My name is..."
);
?>

index.php:

<div id="about">
   <h2><?php echo $lang['about-h2']; ?></h2>
   <p><?php echo $lang['about-p']; ?></p>
</div>

I'm using hypens (about-h2) but I'm not sure if this will cause me problems in the future. Any suggestions?

like image 827
alexchenco Avatar asked Feb 23 '10 14:02

alexchenco


2 Answers

Between camel case and underscores it's personal taste. I'd recommend using whatever convention you use for regular variable names, so you're not left thinking "was this one underscores or camel case...?" and your successor isn't left thinking about all the ways they could torture you for mixing styles. Choose one and stick to it across the board.

That's why hyphens is a very bad idea - also, rarely, you'll want to use something like extract which takes an array and converts its members into regular variables:

$array = array("hello" => "hi", "what-up" => "yup");
extract($array);
echo $hello; // hi
echo $what-up; // FAIL

Personally, I prefer camel case, because it's fewer characters.

like image 158
nickf Avatar answered Oct 02 '22 22:10

nickf


I'm actually surprised no one said this yet. I find it actually pretty bad that everyone brings up variable naming standards when we are talking about array keys, not variables.

Functionally wise, you will not have any problems using hyphens, underscores, camelCase in your array keys. You can even use spaces, new lines or null bytes if you want! It will not impact your code's functionality^.

Array keys are either int or string. When you use a string as a key, it is treated as any other string in your code.

That being said, if you are building a standardized data structure, you are better off using the same standard you are using for your variables names.


^ Unless you are planning to typecast to a (stdClass) or use extract(), in which case you should use keys which convert to valid variable names in order to avoid using ->{"My Key Is"} instead of ->myKeyIs. In which case, make sure your keys conform to [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

like image 20
Andrew Moore Avatar answered Oct 02 '22 23:10

Andrew Moore