1
0
mirror of https://github.com/php/doc-es.git synced 2026-03-23 23:12:09 +01:00
Files
2025-08-28 19:59:08 +02:00

333 lines
8.0 KiB
XML

<?xml version="1.0" encoding="utf-8"?>
<!-- EN-Revision: ba7093cf7f30dbcd301c62536ac7ef8664d891f4 Maintainer: PhilDaiguille Status: ready -->
<!-- Reviewed: no -->
<sect1 xml:id="control-structures.foreach" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
<title>foreach</title>
<?phpdoc print-version-for="foreach"?>
<para>
La estructura <literal>foreach</literal> proporciona una forma sencilla de
iterar sobre <type>array</type>s y objetos <interfacename>Traversable</interfacename>.
<literal>foreach</literal> generará un error cuando se utilice con
una variable que contenga un tipo de dato diferente o con una variable no inicializada.
<informalexample>
<simpara>
<literal>foreach</literal> puede obtener opcionalmente la <literal>key</literal> de cada elemento:
</simpara>
<programlisting>
<![CDATA[
foreach (iterable_expression as $value) {
statement_list
}
foreach (iterable_expression as $key => $value) {
statement_list
}
]]>
</programlisting>
</informalexample>
</para>
<simpara>
La primera forma recorre el iterable dado por
<literal>iterable_expression</literal>. En cada iteración, el valor del
elemento actual se asigna a <literal>$value</literal>.
</simpara>
<simpara>
La segunda forma asignará adicionalmente la clave del elemento actual a
la variable <literal>$key</literal> en cada iteración.
</simpara>
<simpara>
Tenga en cuenta que <literal>foreach</literal> no modifica el puntero interno del array,
que es utilizado por funciones como <function>current</function>
y <function>key</function>.
</simpara>
<simpara>
Es posible
<link linkend="language.oop5.iterations">personalizar la iteración de objetos</link>.
</simpara>
<example>
<title>Usos comunes de <literal>foreach</literal></title>
<programlisting role="php">
<![CDATA[
<?php
/* Ejemplo: solo valor */
$array = [1, 2, 3, 17];
foreach ($array as $value) {
echo "Elemento actual de \$array: $value.\n";
}
/* Ejemplo: clave y valor */
$array = [
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
];
foreach ($array as $key => $value) {
echo "Clave: $key => Valor: $value\n";
}
/* Ejemplo: arrays multidimensionales clave-valor */
$grid = [];
$grid[0][0] = "a";
$grid[0][1] = "b";
$grid[1][0] = "y";
$grid[1][1] = "z";
foreach ($grid as $y => $row) {
foreach ($row as $x => $value) {
echo "Valor en posición x=$x y y=$y: $value\n";
}
}
/* Ejemplo: arrays dinámicos */
foreach (range(1, 5) as $value) {
echo "$value\n";
}
?>
]]>
</programlisting>
</example>
<note>
<para>
<literal>foreach</literal> no admite la capacidad de
suprimir mensajes de error utilizando
<link linkend="language.operators.errorcontrol"><literal>@</literal></link>.
</para>
</note>
<sect2 xml:id="control-structures.foreach.list">
<title>Desempaquetar arrays anidados</title>
<?phpdoc print-version-for="foreach.list"?>
<para>
Es posible iterar sobre un array de arrays y desempaquetar el array anidado
en variables de bucle utilizando ya sea
<link linkend="language.types.array.syntax.destructuring">destructuración de arrays</link>
mediante <literal>[]</literal> o utilizando la estructura de lenguaje
<function>list</function> como valor.
<note>
<simpara>
Tenga en cuenta que
<link linkend="language.types.array.syntax.destructuring">destructuración de arrays</link>
mediante <literal>[]</literal> solo es posible a partir de PHP 7.1.0
</simpara>
</note>
</para>
<para>
<informalexample>
<simpara>
En ambos ejemplos siguientes, <literal>$a</literal> se establecerá con
el primer elemento del array anidado y <literal>$b</literal> contendrá
el segundo elemento:
</simpara>
<programlisting role="php">
<![CDATA[
<?php
$array = [
[1, 2],
[3, 4],
];
foreach ($array as [$a, $b]) {
echo "A: $a; B: $b\n";
}
foreach ($array as list($a, $b)) {
echo "A: $a; B: $b\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
A: 1; B: 2
A: 3; B: 4
]]>
</screen>
</informalexample>
</para>
<para>
Cuando se proporcionan menos variables que elementos en el array,
los elementos restantes serán ignorados.
De manera similar, los elementos pueden omitirse utilizando una coma:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$array = [
[1, 2, 5],
[3, 4, 6],
];
foreach ($array as [$a, $b]) {
// Note que no hay $c aquí.
echo "$a $b\n";
}
foreach ($array as [, , $c]) {
// Omitiendo $a y $b
echo "$c\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
1 2
3 4
5
6
]]>
</screen>
</informalexample>
</para>
<para>
Se generará un aviso si no hay suficientes elementos en el array para llenar
el <function>list</function>:
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$array = [
[1, 2],
[3, 4],
];
foreach ($array as [$a, $b, $c]) {
echo "A: $a; B: $b; C: $c\n";
}
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:
Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:
]]>
</screen>
</informalexample>
</para>
</sect2>
<sect2 xml:id="control-structures.foreach.reference">
<title>foreach y referencias</title>
<para>
Es posible modificar directamente elementos de array dentro de un bucle precediendo
<literal>$value</literal> con <literal>&amp;</literal>.
En ese caso el valor será asignado por
<link linkend="language.references">referencia</link>.
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr = [1, 2, 3, 4];
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr es ahora [2, 4, 6, 8]
unset($value); // romper la referencia con el último elemento
?>
]]>
</programlisting>
</informalexample>
</para>
<warning>
<simpara>
La referencia a un <literal>$value</literal> del último elemento del array
permanece incluso después del bucle <literal>foreach</literal>. Se recomienda
destruir estas referencias utilizando <function>unset</function>.
De lo contrario, ocurrirá el siguiente comportamiento:
</simpara>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr = [1, 2, 3, 4];
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr es ahora [2, 4, 6, 8]
// sin un unset($value), $value sigue siendo una referencia al último elemento: $arr[3]
foreach ($arr as $key => $value) {
// $arr[3] se actualizará con cada valor de $arr...
echo "{$key} => {$value} ";
print_r($arr);
}
// ...hasta que finalmente el penúltimo valor se copie sobre el último valor
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
]]>
</screen>
</informalexample>
</warning>
<example>
<title>Iterar los valores de un array constante por referencia</title>
<programlisting role="php">
<![CDATA[
<?php
foreach ([1, 2, 3, 4] as &$value) {
$value = $value * 2;
}
?>
]]>
</programlisting>
</example>
</sect2>
<sect2 role="seealso">
&reftitle.seealso;
<simplelist>
<member><link linkend="language.types.array">array</link></member>
<member><interfacename>Traversable</interfacename></member>
<member><link linkend="language.types.iterable">iterable</link></member>
<member><function>list</function></member>
</simplelist>
</sect2>
</sect1>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->