Is it recommended to create a separate function for checking if all values in an array are negative in PHP?
It is recommended to create a separate function for checking if all values in an array are negative in PHP to improve code readability and reusability. This function can iterate through the array and return true if all values are negative, and false otherwise.
function areAllNegative($array) {
foreach($array as $value) {
if($value >= 0) {
return false;
}
}
return true;
}
$array = [-1, -5, -3, -7];
if(areAllNegative($array)) {
echo "All values in the array are negative.";
} else {
echo "Not all values in the array are negative.";
}
Keywords
Related Questions
- How can PHPMailer be utilized to automatically save sent emails in the "Sent" folder of an IMAP account?
- Can the visibility of a cookie set in a PHP script be changed to make it immediately accessible?
- Is it advisable to use direct output or a function for displaying content based on UserAgent in PHP?