phparrayslaravelassociative-array

How can I check if particular item exists in associative array?


Consider:

[
 {
 "pid": "1",
 "pname": "Burger",
 "price": "20",
 "qnty": "1",
 "pimg": "1.jpg"
 },
 {
 "pid": "2",
 "pname": "Cheese burger",
 "price": "30",
 "qnty": "1",
 "pimg": "2.jpg"
 }
]

I have an array like above. How can I check if the array has particular "pid"?

For an example, if an array has "pid" 1 then display "View button", otherwise display "add to cart button".


Solution

  • $array = [
     {
     "pid": "1",
     "pname": "Burger",
     "price": "20",
     "qnty": "1",
     "pimg": "1.jpg"
     },
     {
     "pid": "2",
     "pname": "Cheese burger",
     "price": "30",
     "qnty": "1",
     "pimg": "2.jpg"
     }
    ]
    

    You can use isset fucntion.

    $key = 1;
    $count =0 ;
    
    foreach($array as $a) {
        if(isset(array_search($key,$a))){
           //your logic to execute if the $key is there in the array
           $count ++;
       }
     }
      if($count==0){
          //add to cart logic
      }