Skip to content

Commit 41ac7e8

Browse files
authored
Added Arr::isList() helper (#39277)
1 parent 7acb44d commit 41ac7e8

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Illuminate/Collections/Arr.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,19 @@ public static function isAssoc(array $array)
393393
return array_keys($keys) !== $keys;
394394
}
395395

396+
/**
397+
* Determines if an array is a list.
398+
*
399+
* An array is a "list" if all array keys are sequential integers starting from 0 with no gaps in between.
400+
*
401+
* @param array $array
402+
* @return bool
403+
*/
404+
public static function isList($array)
405+
{
406+
return ! self::isAssoc($array);
407+
}
408+
396409
/**
397410
* Get a subset of the items from the given array.
398411
*

tests/Support/SupportArrTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -424,6 +424,22 @@ public function testIsAssoc()
424424
$this->assertFalse(Arr::isAssoc(['a', 'b']));
425425
}
426426

427+
public function testIsList()
428+
{
429+
$this->assertTrue(Arr::isList([]));
430+
$this->assertTrue(Arr::isList([1, 2, 3]));
431+
$this->assertTrue(Arr::isList(['foo', 2, 3]));
432+
$this->assertTrue(Arr::isList(['foo', 'bar']));
433+
$this->assertTrue(Arr::isList([0 => 'foo', 'bar']));
434+
$this->assertTrue(Arr::isList([0 => 'foo', 1 => 'bar']));
435+
436+
$this->assertFalse(Arr::isList([1 => 'foo', 'bar']));
437+
$this->assertFalse(Arr::isList([1 => 'foo', 0 => 'bar']));
438+
$this->assertFalse(Arr::isList([0 => 'foo', 'bar' => 'baz']));
439+
$this->assertFalse(Arr::isList([0 => 'foo', 2 => 'bar']));
440+
$this->assertFalse(Arr::isList(['foo' => 'bar', 'baz' => 'qux']));
441+
}
442+
427443
public function testOnly()
428444
{
429445
$array = ['name' => 'Desk', 'price' => 100, 'orders' => 10];

0 commit comments

Comments
 (0)