esle condition not work in foreach loop php

✔ Recommended Answer

Create a boolean variable with false

Iterate over the array and make this variable true in case the user found.

In the last check the final value of the variable and if it is false then show the message No customer found.

Here is a dynamic functional approach:

$data = json_decode($customers, true);function findCustomerInArr($array,$customerName){    $customerFound = false;    foreach($array as $a){        if(strtolower($a['name']) == strtolower($customerName)){            $customerFound = true;            echo $customerName."'s phone is ".$a['phone'].PHP_EOL;            echo $customerName."'s mobile is ".$a['mobile'].PHP_EOL;            break;        }    }    if(false == $customerFound){        echo "No customer found with this name".PHP_EOL;    }}findCustomerInArr($data,'sara');findCustomerInArr($data,'aliveToDie');


Note: You can remove strtolower() in case you want case-sensitive match.

Method #2

In PHP, the else block is not used in conjunction with a foreach loop. The else block is used in combination with if, while, and for loops to execute a block of code when the condition of the loop is not met.

Here's an example of using else with an if statement:

$score = 80; if ($score >= 90) { echo "A grade"; } elseif ($score >= 80) { echo "B grade"; } else { echo "C grade or below"; }

In the above example, the else block is executed when the condition of both the if and the elseif blocks is not met.

If you need to execute some code after a foreach loop is completed, you can simply place that code outside of the loop. For example:

$fruits = array("apple", "banana", "orange"); foreach ($fruits as $fruit) { echo $fruit . "<br>"; } echo "Loop completed";

In the above example, the echo statement after the foreach loop is executed once the loop has completed iterating over all the elements in the $fruits array.


Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755