What is the best way to write an algorithm in PHP to alternate between multiplying numbers by 5 and 4 in a given array?
To alternate between multiplying numbers by 5 and 4 in a given array, we can iterate through the array and use a flag variable to keep track of whether to multiply by 5 or 4. We can toggle the flag variable after each iteration to switch between the two multipliers.
<?php
function alternateMultiply($arr) {
$flag = true; // true for multiplying by 5, false for multiplying by 4
foreach ($arr as $num) {
if ($flag) {
$num *= 5;
} else {
$num *= 4;
}
echo $num . " ";
$flag = !$flag; // toggle the flag
}
}
$array = [1, 2, 3, 4, 5];
alternateMultiply($array);
?>
Keywords
Related Questions
- What is the best practice for rewriting URLs with parameters in PHP for better SEO optimization?
- How can session data loss be prevented in PHP when passing information between multiple pages in an online shop?
- In what scenarios is it advisable to use encryption for storing user data in cookies, and what are the potential risks associated with this practice in PHP development?