I’m curious to know how to echo an array outside a function, for instance, this code prints it within. but what if I just wanted to return the values and echo it outside?
function myArray() {
$arr = array('One', 'Two', 'Three', 'four');
for ($i = 0; $i < count($arr); $i++) {
echo $arr[$i];
}
}
myArray();
Hope that makes sense.
So, it’s not that you would like to echo() outside the loop, it’s that you would like the values within your array to be accessible.
Using the array() function (which is actually a language construct) and offering only values, the array will be “keyed” for you by PHP. These keys begin at 0 and can be accessed with square brackets, like so:
If you wish to build the array within a function, then you need to be aware of scope. Variables set within functions are not accessible outside of functions. In order to achieve this, you need to return the array and capture the return of that function call: