PHP Array Question - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20) +--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23) +--- Thread: PHP Array Question (/showthread.php?tid=9204) |
PHP Array Question - El Forum - 06-16-2008 [eluser]CodeIgniterNewbie[/eluser] I have a method that returns an array. Is there a way to access a specific element of that returned array? For example: Code: // returns the array, but I only want, say, the value of the second element PHP Array Question - El Forum - 06-16-2008 [eluser]usmc[/eluser] [quote author="CodeIgniterNewbie" date="1213686773"]I have a method that returns an array. Is there a way to access a specific element of that returned array? For example: Code: // returns the array, but I only want, say, the value of the second element you can do any one of these (and so much more) Code: $array = $MyObject->GetMyArray(); PHP Array Question - El Forum - 06-16-2008 [eluser]wiredesignz[/eluser] Or simply ask the method to return the array element. Code: function GetMyArray($index = FALSE) PHP Array Question - El Forum - 06-17-2008 [eluser]CodeIgniterNewbie[/eluser] usmc: 1. Your first approach declares a new variable, $you_are_killing_me_smalls. I am trying to avoid declaring a new variable. Instead, I want to access the individual elements of a method that returns an array directly. 2. I'm not too sure what your second approach does. It seems that $this->arrayContainer will always contain an empty array. Also, the call $MyObject->arrayContainer[1]; breaks encapsulation. wiredesignz: 1. Changing the method signature is not an option. Isn't there a way to access element values directly from a method that returns an array? It's possible to apply other array functions to such a result (e.g. count($MyObject->GetMyArray()), etc.). So, why not a way to access particular elements? PHP Array Question - El Forum - 06-17-2008 [eluser]gtech[/eluser] Quote:Your first approach declares a new variable, $you_are_killing_me_smalls. I am trying to avoid declaring a new variable. Instead, I want to access the individual elements of a method that returns an array directly. why? you are not adding any performance hit. PHP Array Question - El Forum - 06-17-2008 [eluser]John_Betong[/eluser] Try this: Code: // if the result is an array PHP Array Question - El Forum - 06-17-2008 [eluser]CodeIgniterNewbie[/eluser] gtech, Assuming that the contents of each element are not memory hogs, then you can say there isn't a performance hit. My elements aren't memory hogs, but my interest in keeping the code from unnecessarily declaring variables (if possible). John_Betong, Your second snippet is what I would like to do. It doesn't work for me either. |