iterator_to_array

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

iterator_to_arrayCopia o iterador em um array

Descrição

iterator_to_array ( Traversable $iterator , bool $use_keys = true ) : array

Copia os elementos de um iterador em um array.

Parâmetros

iterator

O iterador que está sendo copiado.

use_keys

Se as chaves do iterador serão utilizadas como índices.

A partir do PHP 5.5, se uma chave for um array ou um object, um erro warning será gerado. Chaves null serão convertidas em uma string vazia, chaves float serão truncadas em sua parte integer, chaves resource irão gerar um erro warning e serão convertidas para o seu resource ID, e as chaves boolean serão convertidas para inteiros.

Nota:

Se este parâmetro não for definido ou for definido como true, as chaves duplicadas serão sobrescritas. O último valor com aquela chave estará no array retornado. Defina esse parâmetro como false para receber todos os valores em qualquer caso.

Valor Retornado

Um array contendo os elementos do iterator.

Changelog

Versão Descrição
5.5.0 iterator_to_array() recebeu suporte para outros tipos de chave além de integer e string quando o parâmetro use_keys estiver habilitado.
5.2.1 O parâmetro use_keys foi adicionado.

Exemplos

Exemplo #1 Exemplo da iterator_to_array()

<?php
$iterator 
= new ArrayIterator(array('recipe'=>'pancakes''egg''milk''flour'));
var_dump(iterator_to_array($iteratortrue));
var_dump(iterator_to_array($iteratorfalse));
?>

O exemplo acima irá imprimir:

array(4) {
  ["recipe"]=>
  string(8) "pancakes"
  [0]=>
  string(3) "egg"
  [1]=>
  string(4) "milk"
  [2]=>
  string(5) "flour"
}
array(4) {
  [0]=>
  string(8) "pancakes"
  [1]=>
  string(3) "egg"
  [2]=>
  string(4) "milk"
  [3]=>
  string(5) "flour"
}

add a note add a note

User Contributed Notes 5 notes

up
3
jerome at yazo dot net
15 years ago
Using the boolean param :

<?php

$first
= new ArrayIterator( array('k1' => 'a' , 'k2' => 'b''k3' => 'c''k4' => 'd') );
$second = new ArrayIterator( array( 'k1' => 'X', 'k2' => 'Y', 'Z' ) );

$combinedIterator= new AppendIterator();
$combinedIterator->append( $first );
$combinedIterator->append( $second );

var_dump( iterator_to_array($combinedIterator, false) );

?>

will output :

array(7) (
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "X"
  [5]=>
  string(1) "Y"
  [6]=>
  string(1) "Z"
)

<?php

var_dump
( iterator_to_array($combinedIterator, true) );

?>

will output (since keys would merge) :

array(5) (
  ["k1"]=>
  string(1) "X"
  ["k2"]=>
  string(1) "Y"
  ["k3"]=>
  string(1) "c"
  ["k4"]=>
  string(1) "d"
  [0]=>
  string(1) "Z"
)
up
2
joksnet at gmail dot com
9 years ago
To generate an deep array from nested iterators:

<?php
function iterator_to_array_deep(\Traversable $iterator, $use_keys = true) {
   
$array = array();
    foreach (
$iterator as $key => $value) {
        if (
$value instanceof \Iterator) {
           
$value = iterator_to_array_deep($value, $use_keys);
        }
        if (
$use_keys) {
           
$array[$key] = $value;
        } else {
           
$array[] = $value;
        }
    }
    return
$array;
}
?>

I use it to test an iterator: https://gist.github.com/jm42/cb328106f393eeb28751
up
-1
enelar at develop-project dot ru
7 years ago
Generator approach

function scandir_deep($dir)
{
  foreach (scandir($dir) as $key => $value)
    if (in_array($value, [".",".."]))
      continue;
    else if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
      yield $value => scandir_deep($dir . DIRECTORY_SEPARATOR . $value);
    else
      yield $value;
}
up
-2
Harry Willis
8 years ago
When using iterator_to_array() on an SplObjectStorage object, it's advisable to set $use_keys to false.

The resulting array is identical, since the iterator keys produced by SplObjectStorage::key() are always integers from 0 to (COUNT-1). Passing $use_keys=false cuts out the unnecessary calls to SplObjectStorage::key(), giving a slight performance advantage.
up
-4
chad 0x40 herballure 0x2e com
16 years ago
The use_keys parameter was added in one of the 5.2.x releases; it defaults to TRUE. This matches the behavior in PHP 5.1.6, which lacks this parameter.
To Top