Jump to content

PHP Array inside of a function


admiralgeek

Recommended Posts

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") ?>

Link to comment
https://forums.phpfreaks.com/topic/273533-php-array-inside-of-a-function/
Share on other sites

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);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.