w3resource

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 find_last_Index($items, $func)
{
    $keys = array_keys(array_filter($items, $func));

    return array_pop($keys);
}

echo find_last_Index([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 1;
});

echo "\n";
echo find_last_Index([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 0;
});
?>

Sample Output:

2
3

Flowchart:

Flowchart: Get the index of the last element for which the given function returns a truthy value.

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.



Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

PHP: How to find the last day of the month from date?

$a_date = "2009-11-23";
echo date("Y-m-t", strtotime($a_date));

Ref : https://bit.ly/31coSLD

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook