PHP Exercises: Get the index of the last element for which the given function returns a truth value
PHP: Exercise-82 with Solution
Write a PHP program to get the index of the last element for which the given function returns a truth value.
Sample Solution:
PHP Code:
<?php
// Function definition for 'find_last_Index' that takes an array of items and a filtering function as parameters
function find_last_Index($items, $func)
{
// Use 'array_filter' to filter the items based on the given function and retrieve the keys of the filtered items
$keys = array_keys(array_filter($items, $func));
// Use 'array_pop' to retrieve and return the last key from the array of filtered keys
return array_pop($keys);
}
// Call 'find_last_Index' with an array and an anonymous function checking for odd numbers, then display the result using 'echo'
echo find_last_Index([1, 2, 3, 4], function ($n) {
return ($n % 2) === 1;
});
// Display a newline
echo "\n";
// Call 'find_last_Index' with an array and an anonymous function checking for even numbers, then display the result using 'echo'
echo find_last_Index([1, 2, 3, 4], function ($n) {
return ($n % 2) === 0;
});
?>
Sample Output:
2 3
Flowchart:
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a PHP program to get the last element for which the given function returns a truth value.
Next: Write a PHP program to group the elements of an array based on the given function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics