Orasion Posted March 5, 2012 Share Posted March 5, 2012 Hi all, can you give me suggestion how to return value from function like this function returnArray(){ for($i=1; $i<=3; $i++){ return $i; //how to return this as array?? } } when I code "echo" inside the function then call the function it give me output => 123 but when I code "return" inside the function, it will give output => 1 Can you suggest me how to output it as array? Link to comment https://forums.phpfreaks.com/topic/258304-return-value-with-function/ Share on other sites More sharing options...
trq Posted March 5, 2012 Share Posted March 5, 2012 In your example $i isn't an array. function returnArray() { $foo = array(); for($i=1; $i<=3; $i++){ return $foo[] = i; } return $foo; } Will return an array containing the number 1 - 3. Of course you could more easily achieve the same result by using: $foo = range(1,3); Link to comment https://forums.phpfreaks.com/topic/258304-return-value-with-function/#findComment-1324054 Share on other sites More sharing options...
Orasion Posted March 5, 2012 Author Share Posted March 5, 2012 I change my function like you suggest function returnArray(){ $foo = array(); for($i=1; $i<=3; $i++){ return $foo[] = $i; } return $foo; } when I print_r it, it just give me output -> "1" just like before :confused: Link to comment https://forums.phpfreaks.com/topic/258304-return-value-with-function/#findComment-1324057 Share on other sites More sharing options...
trq Posted March 5, 2012 Share Posted March 5, 2012 There is a typo in my reply, should be: function returnArray(){ $foo = array(); for($i=1; $i<=3; $i++){ $foo[] = $i; } return $foo; } Note you don't want to call return part why through the loop. Link to comment https://forums.phpfreaks.com/topic/258304-return-value-with-function/#findComment-1324060 Share on other sites More sharing options...
Orasion Posted March 5, 2012 Author Share Posted March 5, 2012 WORKED!!! Thanks for your suggestion and Note, I will remember it. Link to comment https://forums.phpfreaks.com/topic/258304-return-value-with-function/#findComment-1324063 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.