Transforming an array into a traversable object with PHP
Published on 2024-04-21 • Modified on 2024-04-21
This snippet shows how to transform an array into a traversable object with PHP. A reminder: iterable
is a type hint introduced in PHP 7.1, whereas Traversable
is a PHP interface. In this case, ArrayIterator
implements the Traversable
interface dans and be type hinted with iterable
.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet299Trait
{
public function snippet299(): void
{
$ai = new \ArrayIterator([
'foo' => 'bar',
'dd' => 'DD',
]);
var_dump($ai->getArrayCopy());
$ai->ksort();
var_dump($ai->getArrayCopy(), $ai->count(), is_iterable($ai), is_a($ai, \Traversable::class)); // @phpstan-ignore-line
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc Random snippet