Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 elements 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.

like image 245
Trufa Avatar asked Nov 22 '25 09:11

Trufa


2 Answers

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(""))))  
like image 188
AndreKR Avatar answered Nov 24 '25 22:11

AndreKR


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";
}
like image 23
Orbling Avatar answered Nov 24 '25 22:11

Orbling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!