My code:
$customers='[
{
"id": 1,
"name": "sara",
"phone": 1100,
"mobile": 1111
},
{
"id": 2,
"name": "ben",
"phone": 2200,
"mobile": 2222
}
]';
$data = json_decode($customers, true);
foreach($data as $a){
if($a['name'] == 'sara'){
$phone = $a['phone'];
$mobile = $a['mobile'];
echo "sara's phone is $phone";
echo "sara's mobile is $mobile";
}
else{
echo "No customer found with this name";
}
}
my problem is:
just else part is working and if condition is not working but when i remove else part, if part is working good.
can you help me??
2
Answers
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 messageNo customer found.
Here is a dynamic functional approach:
Output: https://3v4l.org/fIJXu
Note: You can remove
strtolower()
in case you want case-sensitive match.You may Code the loop and condition like this, It may solve the problem.