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');
Output: https://3v4l.org/fIJXu
Note: You can remove strtolower()
in case you want case-sensitive match.
Source: stackoverflow.com
Answered By: Anant - Alive to die
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:
php$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:
php$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.
Comments
Post a Comment