PHP for finding the index of an element in an array


PHP Code for Finding the Index of an Element in an Array

<?php
// Initialize an array
$arr = ['apple', 'banana', 'orange', 'grape', 'pineapple'];

// Function to find the index of an element in an array
function findIndex($arr, $element) {
    // Iterate over the array
    for ($i = 0; $i < count($arr); $i++) {
        // Check if the current element matches the element we're looking for
        if ($arr[$i] === $element) {
            // Return the index of the element if it's found
            return $i;
        }
    }
    // Return -1 if the element is not found
    return -1;
}

// Test the function
$index = findIndex($arr, 'orange');

// Print the index of the element
echo "The index of 'orange' in the array is: $index";

Code Breakdown and Implementation

This PHP code defines a function called findIndex that takes two parameters: an array and an element to search for. It then iterates over the array using a for loop and compares each element with the element we’re looking for. If the element is found, the function returns its index. Otherwise, it returns -1.

Here’s a step-by-step breakdown of how the code works:

  1. Initialize the array: An array $arr is initialized with some elements.

  2. Define the findIndex function: This function takes two parameters: $arr (the array) and $element (the element to search for).

  3. Iterate over the array: The function uses a for loop to iterate over the elements of the array.

  4. Compare each element: Inside the loop, the code checks if the current element $arr[$i] is equal to the element we’re looking for $element.

  5. Return the index: If the element is found, the function returns the value of $i, which represents the index of the element in the array.

  6. Return -1 if not found: If the element is not found after iterating through the entire array, the function returns -1.

  7. Test the function: The code calls the findIndex function with the $arr and ‘orange’ as arguments and stores the result in $index.

  8. Print the index: Finally, the code prints the index of the element in the array using echo.

This solution efficiently finds the index of the specified element in the array using a straightforward iteration and comparison approach.