Laravel Check if key exists in an Array Example

In this example, I explain how to check if key exists in an array using laravel. We will show example of laravel check if key exists in an array using laravel Arr::has() method. Laravel Arr::has() function to you can check specific key or element exists in an array using dot notation.

Also, Laravel Arr::has() method to you can check item or key exists in multi dimensional array.

Read Also :  Laravel 8 Create Factory Tinker Example

Example : Check if key exists in an array

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Arr;

class UserController extends Controller
{
    public function index(){        
        $array = ['product' => ['name' => 'Desk', 'price' => 100]];

        if (Arr::has($array, 'product.name')){
            echo 'Item is exists';
        }else{
            echo 'Item is not exists';
        }

        echo "<br>";
        // true

        if(Arr::has($array, ['product.price', 'product.discount'])){
            echo 'Item is exists';
        }else{
            echo 'Item is not exists';
        }

        // false
    }
}

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('users', [UserController::class,'index']);

I hope you understand how to check if key or item exists in an array and it can help you….