string inside array, quotes or no quotes
When i assign a key value into an array of type string, does it have to be in quotes?
define('ALBUM_COVER_50', '../discography/artwork/cover/50/');
define('ALBUM_COVER_ZOOM', '../discography/artwork/cover/800/');
$selected_artwork = array();
$cover = 'greatesthits_cs23409.jpg';
$开发者_如何学Cselected_artwork[ALBUM_COVER_50.$cover] = ALBUM_COVER_ZOOM.$cover;
In the above snippet, do i have to put ALBUM_COVER_50.$cover
in quotes like:
$selected_artwork['\''.ALBUM_COVER_50.$cover.'\''] = ALBUM_COVER_ZOOM.$cover;
What is the best practice to go about this issue?
No, it does not need to be in quotes if you use a variable or defined constant as the array key. You should think of the key you use as a string value itself. PHP will process it as it does any other string value, which means you can use variables, double-quoted variable interpolation, concatenation, or anything you need to construct an array key.
If it improves readability, I will often store the needed array key into a variable. Recently I needed to do this because the array key was the result of 3 or 4 string concatenations and it was unwieldy to read.
// To improve readability
// instead of performing string operations inside the array key []
$selected_artwork[ALBUM_COVER_50.$cover] = ALBUM_COVER_ZOOM.$cover;
// becomes...
$k = ALBUM_COVER_50.$cover;
$selected_artwork[$k] = ALBUM_COVER_ZOOM.$cover;
No quotes are required in this case.
If you place ALBUM_COVER_50
in quotes, it will cease to be a constant and will become a string containing the value 'ALBUM_COVER_50'. This is unlikely to produce the results you expect.
The same is true with $cover
. This variable already contains a string ('greatesthits_cs23409.jpg'). If you place it in single quotes, it will cease to contain that value, and will just be a string with the value '$cover'.
If you use single quote in the way you indicated:
'\''.ALBUM_COVER_50.$cover.'\''
You will create an array key that looks like this:
['\'../discography/artwork/cover/50/greatesthits_cs23409.jpg\'']
You may just drop the quotes.
精彩评论