How can PHP functions like in_array() and array_search() be used to find alternative products from a relationsArray?

To find alternative products from a relationsArray using PHP functions like in_array() and array_search(), we can iterate through the array and check if the desired product exists in the relationsArray. If it does, we can then retrieve the alternative products associated with it. We can use array_search() to find the index of the desired product and then access the alternative products using that index.

$desiredProduct = "ProductA";
$relationsArray = [
    "ProductA" => ["ProductB", "ProductC"],
    "ProductB" => ["ProductA", "ProductD"],
    "ProductC" => ["ProductA", "ProductE"]
];

if (array_key_exists($desiredProduct, $relationsArray)) {
    $alternativeProducts = $relationsArray[$desiredProduct];
    echo "Alternative products for $desiredProduct are: " . implode(", ", $alternativeProducts);
} else {
    echo "No alternative products found for $desiredProduct.";
}