PHP to list all indices of an array whose values meet a condition
PHP Code:
<?php
// Input array
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Condition to check
$condition = function ($value) {
return $value % 2 == 0;
};
// Get all indices satisfying the condition
$indices = array_filter(array_keys($arr), $condition);
// Print the indices
print_r($indices);
?>
Explanation:
-
Define an input array
$arr
with sample values. -
Create an anonymous function
$condition
to check if a value is even (divisible by 2). -
Use
array_filter
to go through each element in$arr
and filter out the keys (indices) that satisfy the condition specified in$condition
. -
The result of
array_filter
is stored in the$indices
variable. -
Finally, print the
$indices
array to display the indices of the even numbers in$arr
.
Implementation:
To effectively implement this solution, consider the following:
-
Time Complexity:
array_filter
has a time complexity of O(n), where n is the number of elements in the array. -
Memory Usage: The solution uses an additional array (
$indices
) to store the valid indices, so it requires O(n) extra memory. -
Handling Empty Arrays: Check if the input array is empty before applying
array_filter
to avoid errors or incorrect results. -
Custom Conditions: You can modify the
$condition
function to specify any desired condition for filtering the indices. For example, you could check for odd numbers, values within a certain range, or any other custom criteria. -
Additional Features: You can enhance the solution by adding error handling, supporting multiple conditions, or returning the values instead of the indices.