Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a value exits 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?

like image 290
Funny Frontend Avatar asked Feb 02 '16 07:02

Funny Frontend


People also ask

How check value exist in array or not in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do you check if a array contains a specific word in PHP?

Answer: Use the PHP strpos() Function You can use the PHP strpos() function to check whether a string contains a specific word or not. The strpos() function returns the position of the first occurrence of a substring in a string.


2 Answers

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";

}
like image 148
Hassaan Avatar answered Oct 09 '22 17:10

Hassaan


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

like image 26
Qazi Avatar answered Oct 09 '22 17:10

Qazi