开发者

Check for repeated elements in PHP array (if not empty)

Hi lets say I've got this array:

$check_post = array(

 $_POST["a_post"],
 $_POST["b_post"],
 $_POST["c_post"],
 $_POST["d_post"],
 $_POST["e_post"],
 $_POST["f_post"],
 $_POST["g_post"],
 $_POST["h_post"],
 $_POST["i_post"]

 );

I want to check whether any e开发者_JAVA百科lements of this array are repeated, so the best I got is this:

if (count(array_unique($check_post)) < count($check_post))  
    echo "Duplicate";  
else  
    echo "NO Duplicate";

Which works fine except for the fact that if more that one textarea is left blank (which is allowed) it gives me FALSE.

What I want is to NOT consider the empty values of the array for the (count(array_unique())

BTW I have tried with empty() and with array_values($check_post) but I cant get around it.

Thanks in advance!! please ask for any needed clarification.


To remove all the empty values from the comparison you can add array_diff():

if (count(array_unique(array_diff($check_post,array("")))) < count(array_diff($check_post,array(""))))  


Well the way you have it is fine, though as you say, you have a need to remove the empty entries first.

$non_empty_check_post = array_filter($check_post, create_function('$item', 'return !empty($item);');

if (count(array_unique($non_empty_check_post)) < count($non_empty_check_post)) {
    echo "Duplicate";
} else {
    echo "NO Duplicate";
}


Filter out the blanks from your array:

function no_blanks($val) {
    // Do not use empty() here if you don't consider the string "0" as blank
    return trim($val) !== '';
}

$check_post = array_filter($check_post, 'no_blanks');

if (count(array_unique($check_post)) < count($check_post))  
    echo "Duplicate";  
else  
    echo "NO Duplicate";


if (count(array_unique(array_filter(function(x) {return !empty(x)}, $check_post)) < count($check_post))  
    echo "Duplicate";  
else  
    echo "NO Duplicate";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜