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
$arrwith sample values. -
Create an anonymous function
$conditionto check if a value is even (divisible by 2). -
Use
array_filterto go through each element in$arrand filter out the keys (indices) that satisfy the condition specified in$condition. -
The result of
array_filteris stored in the$indicesvariable. -
Finally, print the
$indicesarray to display the indices of the even numbers in$arr.
Implementation:
To effectively implement this solution, consider the following:
-
Time Complexity:
array_filterhas 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_filterto avoid errors or incorrect results. -
Custom Conditions: You can modify the
$conditionfunction 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.