Laravel Collections difference between contains() & containsStrict() Methods

In this post, we will see about difference between contains() & containsStrict() Methods

contains() Method


if we Look contains() method Syntax:


/**
     * Determine if an item exists in the enumerable.
     *
     * @param  mixed  $key
     * @param  mixed  $operator
     * @param  mixed  $value
     * @return bool
     */
    public function contains($key, $operator = null, $value = null);


contains() if an element exists in the collection matching a given truth other wise it return false .let see example

$collection = collect([
        'apple',
        'samsung',
        'xiaomi',
        'oppo'
    ]);
    $collection->contains('apple'); //true

    $collection->contains('htc'); //false


we can see apple is exists then it will return true and htc not exists then it will return false


Problem with contains() method


$collection = collect([
        [
            'brand' => 'apple',
            'price' => '10000'
        ],
        [
            'brand' => 'samsung',
            'price' => 50000
        ],
    ]);
    $mobile = $collection->contains('price', 10000); //true

    $mobile = $collection->contains('price', '10000'); //true
    dd($mobile);


we can see contains method check only string it not check integer value you can see in price contain return both true which is right

how to solve this issue we can use containsStrict() Method


containsStrict() Methods


This method has the same signature as the contains method; however, all values are compared using "strict" comparisons.

/**
     * Determine if an item exists, using strict comparison.
     *
     * @param  mixed  $key
     * @param  mixed  $value
     * @return bool
     */
    public function containsStrict($key, $value = null);


example


$collection = collect([
        [
            'brand' => 'apple',
            'price' => '10000'
        ],
        [
            'brand' => 'samsung',
            'price' => 50000
        ],
    ]);
    $mobile = $collection->containsStrict('price', '10000'); //true

    $mobile = $collection->containsStrict('price', 10000); //false

    dd($mobile);


you can see it strict check value string or integer


Tags: