skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. You may Code the loop and condition like this, It may solve the problem.

    $customers = '[
     {
      "id": 1,
      "name": "sara",
      "phone": 1100,
      "mobile": 1111
     },
     {
      "id": 2,
      "name": "ben",
      "phone": 2200,
      "mobile": 2222
     }
    ]';
    $data = json_decode($customers, true);
    
    $phone = Null;
    $mobile = Null;
    $name="sara";
    
    foreach ($data as $a) {
       if ($a['name'] == $name) {
          $phone = $a['phone'];
          $mobile = $a['mobile'];
          break;
       }
    }
    
    if ($phone != Null && $mobile != Null) {
       echo "$name's phone is $phone n";
       echo "$name's mobile is $mobile";
    }else{
       echo "No customer found with this name";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search