Funny Frontend
Funny Frontend

Reputation: 3925

Check if a value exists in array (Laravel or Php)

I have this array:

$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');

With a die() + var_dump() this array return me:

array:2 [▼
  0 => "hc1wXBL7zCsdfMu"
  1 => "dhdsfHddfD"
  2 => "otheridshere"
]

I want check if a design_id exists in $list_desings_ids array.

For example:

foreach($general_list_designs as $key_design=>$design) {
    #$desing->desing_id return me for example: hc1wXBL7zCsdfMu
    if(array_key_exists($design->design_id, $list_desings_ids))
    $final_designs[] = $design;
}

But this not works to me, what is the correct way?

Upvotes: 43

Views: 204377

Answers (5)

Mujahid Khan
Mujahid Khan

Reputation: 1834

use Illuminate\Support\Collection;

First import above class then write below code

 $list = new Collection(['hc1wXBL7zCsdfMu', 'dhdsfHddfD', 'otheridshere']);
            $id = 'hc1wXBL7zCsdfMu';
            if ($list->contains($id)) {
                //yes: $id exits in array
            }

Upvotes: 3

Hassaan
Hassaan

Reputation: 7662

You can use in_array for this.

Try

$design_id = 'hc1wXBL7zCsdfMu';
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');

if(in_array($design_id, $list_desings_ids))
{
  echo "Yes, design_id: $design_id exits in array";

}

Upvotes: 66

Pratik Bhalodiya
Pratik Bhalodiya

Reputation: 744

you need to change only your condition replace with that code

if(in_array($design->design_id, $list_desings_ids))

Upvotes: 15

paranoid
paranoid

Reputation: 7105

Your array not have key .
try this

foreach($general_list_designs as $key_design=>$design) {
       #$desing->desing_id return me for example: hc1wXBL7zCsdfMu
       if(in_array($design->design_id, $list_desings_ids))
       $final_designs[] = $design;
 }

Upvotes: 8

Qazi
Qazi

Reputation: 5135

instead array_key_exists you just type in_array this will solve your issue because if you dump your this array

$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');

output will be,

array(
   0 => hc1wXBL7zCsdfMu,
   1 => dhdsfHddfD,
   2 => otheridshere
)

so your code array_key_exists will not work, because here in keys 0,1,2 exists, So, you want to check values,so for values, just do this in_array it will search for your desire value in your mentioned/created array

Upvotes: 29

Related Questions