user56489870 user56489870 - 1 year ago 54
PHP Question

how to know if an array of indexed arrays had the same value more than once?

I have this array

$products[0]['productid'] = 5;
$products[0]['name'] = "apples";
$products[0]['seller'] = 1;

$products[1]['productid'] = 15;
$products[1]['name'] = "orange";
$products[1]['seller'] = 1;

$products[2]['productid'] = 5;
$products[2]['name'] = "apples";
$products[2]['seller'] = 2;
// .... more 5000 products

this array is filled by the client with ajax. I need to make a restriction that
array don't have the same
in any of it's other members.
as in the invalid data example above

What I do to get that done is by doing this

$onlyids = array();
for($x=0; $x < count($products); $x++){
$onlyids[]=$products[$x]['productid'];//get only productid in an array
//remove duplicate members
$onlyids2= array_unique($onlyids);
//check if there were duplicates
if(count($onlyids) != count($onlyids2)){
//same id found, reject client inputs

did I do it correct ? or there is a better performing way. because my way is obviously consume more time on big arrays?

Answer Source

Probably the most performant way is to store found product ids as array keys while you iterate the data:

$productIds = [];

foreach ($products as $product) {
    if (isset($productIds[$product['productid']])) {
        throw new Exception('Duplicate product id ' . $product['productid']);
    $productIds[$product['productid']] = true;

echo 'All good';

More obscure and inefficient, but a one-liner:

if (max(array_count_values(array_column($products, 'productid'))) > 1) {
    throw new Exception('Invalid input');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download