Implementing in_array Without Built-in PHP Functions

What is in_array in PHP?

in_array is a built-in PHP function used to check if a specific value exists within an array. It returns true if the value is found and false if it is not. This function is case-sensitive and can also perform strict type comparisons when enabled.

Syntaxt:

in_array(mixed $needle, array $haystack, bool $strict = false): bool

Example:

<?php
$fruits = ["apple", "banana", "orange"];
if (in_array("banana", $fruits)) {
    echo "Banana is in the list!";
} else {
    echo "Banana is not in the list!";
}
?>

in_array Without Built-in PHP Functions

Example:

<?php
// Sample input array and value to search
$inputArray = [10, 20, 30, 40, 50];
$searchValue = 30;

// Function to check if a value exists in an array
function customInArray($value, $array) {
    foreach ($array as $element) {
        if ($element === $value) {
            return true; // Value found in the array
        }
    }
    return false; // Value not found
}

// Call the function and display the result
if (customInArray($searchValue, $inputArray)) {
    echo "The value $searchValue exists in the array.";
} else {
    echo "The value $searchValue does not exist in the array.";
}
?>

Output:

The value 30 exists in the array.

This post demonstrates how to replicate the functionality of PHP’s in_array without using any built-in array functions. The customInArray function iterates through the array using a foreach loop and checks each element against the provided value. If a match is found, the function returns true; otherwise, it returns false.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *