[Basic PHP] Treat function or method call as an array? |
[eluser]janogarcia[/eluser]
I have these values Code: $CI->config->item('returns_indexed_array'); This works... Code: $array = $CI->config->item('returns_indexed_array'); ...but, what if I don't want to create those temporary variables $array and $index? Is it possible to get the value in one shot? This wouldn't work... Any simple workaround? Am I missing something? Code: $value = $CI->config->item('returns_indexed_array')[$CI->config->item('returns_index')]; Found in stack overflow: Quote:Unfortunately, you cannot treat function return values as arrays in PHP. You have to assign the value explicitly.
[eluser]danmontgomery[/eluser]
Like the stack overflow post says, you can't treat return values as arrays. You can get rid of one of your lines, though. Code: $array = $CI->config->item('returns_indexed_array'); You could also just write a helper function so that it would at least look cleaner.
[eluser]janogarcia[/eluser]
Thank you noctrum for the fast reply. (the snippet I posted is not actual production code, it was an illustrative example, I could have used the config_item() helper function of Common.php to the same effect: $array = config_item('some_array'); $index = config_item('some_index');...)
[eluser]danmontgomery[/eluser]
You can use array_* functions on the result, which may not be much help if you're looking for a specific index, bout you could do something like Code: $value = array_pop($CI->config->item('returns_indexed_array')); Or any (I haven't tested them all, but I'm thinking any of them should work) of the array functions... Depending on your specific needs you may be able to work something out that way.
[eluser]janogarcia[/eluser]
Just found this snippet at the PHP documentation (curiosly enough it was submitted a few weeks ago) http://www.php.net/manual/en/language.ty....php#95210 Quote:If you ever wondered if you can do something like: This could be an interesting addition to the array_helper.php (I'd modify the error handling routine to be more "CI friendly") if you find yourself using many unnecessary temporary variables. |
Welcome Guest, Not a member yet? Register Sign In |