admiralgeek Posted January 23, 2013 Share Posted January 23, 2013 Hi, I am trying to output an array inside of an function but all I get is one out put, it is as if the foreach loop is not working. Any help? <?php function writeValue($value) { $PCR=array($value); foreach($PCR as $value) { echo $value; } } ?> <?php writeValue("one","two","three","ect") ?> Quote Link to comment https://forums.phpfreaks.com/topic/273533-php-array-inside-of-a-function/ Share on other sites More sharing options...
gristoi Posted January 23, 2013 Share Posted January 23, 2013 it is because you are only expecting the first parameter ("one") to be passed in the function function writeValue(array $value) { foreach($value as $output) { print $output.PHP_EOL; } } <?php writeValue(array('one','two','three','four')); . Quote Link to comment https://forums.phpfreaks.com/topic/273533-php-array-inside-of-a-function/#findComment-1407692 Share on other sites More sharing options...
Barand Posted January 23, 2013 Share Posted January 23, 2013 or you can use func_get_args if you want to send them as separate values Quote Link to comment https://forums.phpfreaks.com/topic/273533-php-array-inside-of-a-function/#findComment-1407693 Share on other sites More sharing options...
admiralgeek Posted January 23, 2013 Author Share Posted January 23, 2013 Thank you, I had to replace PHP_EOL with html formatted <br />, in order for each value to have a newline. Quote Link to comment https://forums.phpfreaks.com/topic/273533-php-array-inside-of-a-function/#findComment-1407695 Share on other sites More sharing options...
PaulRyan Posted January 23, 2013 Share Posted January 23, 2013 (edited) You shouldn't really echo or print from a function as it doesn't do as you expect. Return the value from the function and assign it to a variable, then use that variable to display its value. <?PHP function writeValue($value) { //### Check to make sure an array was provided if(!is_array($value)) { $finalOutput = 'You did not provide an array.'; //### If an array is provided add each element to the output } else { $finalOutput = ''; //### Foreach element add it to the output foreach($value AS $output) { $finalOutput .= $output . PHP_EOL; } } //### Return the output, don't echo return $finalOutput; } //### Echo output from function $functionOutput = writeValue(array('one','two','three','four')); echo nl2br($functionOutput); ?> Edited January 23, 2013 by PaulRyan Quote Link to comment https://forums.phpfreaks.com/topic/273533-php-array-inside-of-a-function/#findComment-1407702 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.