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

Edited by PaulRyan
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.