Skip to content

Array Assertions

Array assertions validate arrays, collections, and array-accessible objects.

Assert that a value is countable.

use Cline\Assert\Assertions\Assertion;
Assertion::isCountable($array);
Assertion::isCountable($collection, 'Value must be countable');

Assert exact number of elements.

Assertion::count($array, 5);
Assertion::count($items, 3, 'Must have exactly 3 items');

Assert minimum number of elements.

Assertion::minCount($array, 1);
Assertion::minCount($options, 2, 'Must provide at least 2 options');

Assert maximum number of elements.

Assertion::maxCount($array, 10);
Assertion::maxCount($tags, 5, 'Maximum 5 tags allowed');

Assert that a key exists.

Assertion::keyExists($array, 'name');
Assertion::keyExists($config, 'database', 'Database configuration is required');

Assert that a key does NOT exist.

Assertion::keyNotExists($array, 'legacy_field');
Assertion::keyNotExists($data, 'password', 'Password should not be included');

Assert that a key exists and its value is not empty.

Assertion::notEmptyKey($data, 'name');
Assertion::notEmptyKey($form, 'email', 'Email field cannot be empty');

Assert all values are unique.

Assertion::uniqueValues($array);
Assertion::uniqueValues($ids, 'All IDs must be unique');

Assert that a value exists in an array.

Assertion::inArray($status, ['draft', 'published', 'archived']);
Assertion::inArray($role, $validRoles, 'Invalid role selected');

Assert that a value does NOT exist in an array.

Assertion::notInArray($username, $bannedNames);
Assertion::notInArray($value, $blacklist, 'This value is not allowed');

Alias for inArray().

Assertion::choice($color, ['red', 'green', 'blue']);

Assert that an array contains a subset.

$expected = ['name' => 'John', 'active' => true];
Assertion::eqArraySubset($user, $expected);
use Cline\Assert\Assert;
Assert::that($array)
->isArray()
->notEmpty()
->minCount(1)
->maxCount(10);
Assert::that($status)
->string()
->inArray(['pending', 'approved', 'rejected']);
Assert::that($config)
->isArray()
->keyExists('host')
->keyExists('port')
->keyExists('database');
Assert::lazy()
->that($form, 'form')->isArray()
->that($form, 'form')->keyExists('name')
->that($form, 'form')->notEmptyKey('name')
->verifyNow();
Assert::that($items)
->isArray()
->minCount(1, 'At least one item is required')
->maxCount(100, 'Maximum 100 items allowed');

Use the all() modifier to validate every element:

Assert::thatAll($tags)->string();
Assert::thatAll($quantities)
->integer()
->greaterThan(0);
Assert::thatAll($emailList)->email();
Assert::that($data)
->isArray()
->keyExists('user')
->keyExists('settings');
Assert::that($data['user'])
->isArray()
->notEmptyKey('id')
->notEmptyKey('name');