John Davidson

php - How to read comment inside an array

0 comments
Message:


Lets say I have this array:


$arr = [
"UK" #United Kingdom
,"USA" #United States
,"BR" #Brazil
];

Is it possible to loop through the array AND a part from the value itself also get the comment?
Of course I could make this to a key/value array. But as there are so many entries I wonder if I can take advantage of the comments.


Basically I would need to do:


foreach($arr as $key=>value) {
echo 'Code: ' . $key . PHP_EOL;
echo 'Name: ' . $value . PHP_EOL;
}

Doing this today it is of course giving me the array index as key and the code as value.



My Answer:
Unfortunately, it is not possible to directly access comments inside an array in PHP. Comments are ignored by the PHP interpreter and are not stored in memory during runtime.

If you need to associate additional information with each value in the array, you can use a key/value pair array as you mentioned. This way, you can easily access both the code and the name associated with it.

Alternatively, you could create a separate array or data structure to store the comments and then access them based on the index of the main array.

Here is an example using a key/value pair array:

php
$arr = [
"UK" => "United Kingdom",
"USA" => "United States",
"BR" => "Brazil"
];

foreach($arr as $key => $value) {
echo 'Code: ' . $key . PHP_EOL;
echo 'Name: ' . $value . PHP_EOL;
}


This way, you can easily access both the code and the name associated with each value in the array.

Rate this post

4 of 5 based on 7714 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us