So I have an array called $messages, and I want to output messages through the array within different functions.
function validateNumber($number) {
if(!is_numeric($number)) {
$messages[] = 'This aint a number bro';
return $messages;
}
}
On my view i have
foreach($messages as $message) {
echo $message;
}
Why is this not working? I want to it to echo out the message on the foreach I have.
Before you can use the messages you need to return it because $messages
is only available inside your validateNumber
function.
$messages = validateNumber($number);
foreach($messages as $message) {
echo $message;
}
If validateNumber
only contains this one if clause it does not really make sense to add the message to an array. You can simply return it as a string and use the result:
function validateNumber($number) {
if(!is_numeric($number)) {
$message = 'This aint a number bro';
return $message;
}
}
You call it the same way:
$message = validateNumber($number);