检查数组中是否存在值(Laravel或Php)

时间:2016-02-02 07:23:29

标签: php arrays laravel

我有这个数组:

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

使用die()+ var_dumo()这个数组返回我:

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

我想检查一下design_id是否退出$ list_desings_ids数组。

例如:

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

但这对我不起作用,正确的方法是什么?

5 个答案:

答案 0 :(得分:15)

您可以使用in_array

尝试

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

}

答案 1 :(得分:13)

代替array_key_exists您只需输入in_array即可解决您的问题 因为如果你转储这个数组

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

输出将是,

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

因此您的代码array_key_exists将无效,因为此处的密钥0,1,2存在,因此,您要检查值,因此对于值,只需执行此操作in_array它将搜索你提到/创建的数组中的欲望值

答案 2 :(得分:4)

你的阵列没有钥匙 试试这个

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

答案 3 :(得分:4)

您只需要更改条件替换为该代码

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

答案 4 :(得分:1)

use Illuminate\Support\Collection;

先导入上面的类然后写下面的代码

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