我有一个带管道符号的字符串我需要检查每个管道值是否包含在$ attrib数组
所以如果每个值都显示成功或显示错误。
PHP
<?php
$fields = "NAME|PHONE|EMAIL";
$get_each_val = expolde('|',$fields)
$attribs = array
(
"NAME" => "Jony",
"EMAIL" => "jonyJoe@abc.com",
"LOCATION" => "Xyz",
"ADDRESS" => "23 Street",
"MESSAGE" => "Hi there!"
);
//need to check
if $get_each_val // exploded from $fields
contain in
array_keys($attribs)
if
//$get_each_val is present in $attribs
echo $get_each_val.' - success<br/>';
else
echo $get_each_val.' - error <br/>';
?>
输出类似:
NAME - success
PHONE - error
EMAIL - success
答案 0 :(得分:1)
使用内置函数array_key_exists()函数检查密钥是否存在。
<?php
$fields = "NAME|PHONE|EMAIL";
$get_each_val = explode('|',$fields);
$attribs = array (
"NAME"=> "Jony",
"EMAIL"=> "jonyJoe@abc.com",
"LOCATION"=> "Xyz",
"ADDRESS"=> "23 Street",
"MESSAGE"=> "Hi there!"
);
foreach ($get_each_val as $value) {
if(array_key_exists($value, $attribs)){
echo $value.'- success<br/>';
}else{
echo $value.'- error<br/>';
}
}
?>
答案 1 :(得分:0)
您可以使用以下代码:
<?php
$fields = "NAME|PHONE|EMAIL";
$get_each_val = explode('|',$fields);
$attribs = array
(
"NAME"=> "Jony",
"EMAIL"=> "jonyJoe@abc.com",
"LOCATION"=> "Xyz",
"ADDRESS"=> "23 Street",
"MESSAGE"=> "Hi there!"
);
foreach ($get_each_val as $value) {
if(isset($attribs[$value]))
{
echo $value.' - success<br/>';
}
else
{
echo $value.' - error <br/>';
}
}
?>