Nielsapp
Nielsapp

Reputation: 302

How to check whether an array of items contains only this item?

$items1 = ['apple', 'tree', 'juice'];
$items2 = ['apple', 'tree'];
$items3 = ['apple'];

// loop
If ($items[i].containsOnly['apple'])
{
  // do something..
}

In the simplified example above I want to get the array that matches the given item. Is there a method available similar to 'containsOnly'? Or what is the best way to do this?

Upvotes: 2

Views: 879

Answers (5)

Deepak A
Deepak A

Reputation: 1636

//If the array has the only item present    
   if(in_array('apple',$item) && count($item)==1)
    {
    //Do Something
    }

Upvotes: 5

thisiskelvin
thisiskelvin

Reputation: 4202

You could create a collection of item groups, ->filter() by the condition, then run code on ->each item group which passed the condition.

$itemGroups[] = ['apple', 'tree', 'juice'];
$itemGroups[] = ['apple', 'tree'];
$itemGroups[] = ['apple'];

collect($itemGroups)
    ->filter(function($items, $key) {
        return count($items) == 1 && in_array('apple', $items);
    })
    ->each(function($items, $key) {
        // do something
    });

Upvotes: 3

PHP Geek
PHP Geek

Reputation: 4033

try this:

 $items=array_merge($items1,$items2,$items3);
    if (in_array("apple", $items)){
        echo "success";
    }

Upvotes: 0

Script47
Script47

Reputation: 14540

Couple your logic with count:

function containsOnly($a, $v)
{
    return count($a) === 1 && array_values($a)[0] === $v; 
}

This will ensure that you have only one item and the value is equal to what you are searching for.

Note: The usage of array_values here is to reset all the indexes so we can ensure [0] is where the value will be. Instead of the array_values variation you can use in_array if you prefer that.

Upvotes: 3

Bruno Francisco
Bruno Francisco

Reputation: 4218

You can use the method contains. From the Laravel documentation:

$collection = collect(['name' => 'Desk', 'price' => 100]);

$collection->contains('Desk');

// true

$collection->contains('New York');

// false

I think the example is fairly simple. In your example it would look something like:

$collection = $items1->merge($items2)->merge($items3)
if($collection->contains('apple') && $collection->count() === 1){
  // it contains apple
}

Not tested tho but you get the idea behind it.

Upvotes: 0

Related Questions