← PHP EspañolChapter 06 of 13

Arreglos

## Objetivos de Aprendizaje - Comprender arreglos indexados - Trabajar con arreglos asociativos - Manejar arreglos multidimensionales - Dominar funciones de arreglos ## Creando Arreglos ### Arreglo Básico ```php ``` ### Sintaxis array() ```php ``` ## Arreglos Indexados ### Creando ```php ``` ### Agregando Elementos ```php red, [1] => green, [2] => blue, [3] => yellow, [4] => purple ?> ``` ### Eliminando Elementos ```php green unset($colors[0]); // Remove by index $colors = array_values($colors); // Re-index ?> ``` ## Arreglos Asociativos ### Creando Arreglos Asociativos ```php "Alice", "age" => 25, "city" => "Paris" ]; echo $person["name"]; // Alice ?> ``` ### Agregando/Actualizando ```php "123-456", "country" => "France"]); ?> ``` ### Eliminando ```php "Alice", "age" => 25, "city" => "Paris"]; unset($person["city"]); // Remove city print_r($person); // [name] => Alice, [age] => 25 ?> ``` ## Iteración de Arreglos ### Bucle for (Indexados) ```php ``` ### Bucle foreach ```php $fruit) { echo "$index: $fruit\n"; } // By key-value (associative) foreach ($person as $key => $value) { echo "$key: $value\n"; } ?> ``` ## Arreglos Multidimensionales ### Arreglo 2D ```php ``` ### Asociativo con Arreglos ```php ["math" => 95, "science" => 88], "Bob" => ["math" => 78, "science" => 92] ]; echo $students["Alice"]["math"]; // 95 ?> ``` ### Iterando Arreglo 2D ```php ``` ## Funciones de Arreglos ### Conteo y Tamaño ```php ``` ### Verificando Claves/Valores ```php "Alice", "age" => 25]; isset($person["name"]); // true array_key_exists("name", $person); // true in_array(25, $person); // false (25 is not a value) in_array("Alice", $person); // true array_keys($person); // ["name", "age"] array_values($person); // ["Alice", 25] ?> ``` ### Buscando ```php ``` ### Rebanando ```php 10, 1 => 20, 2 => 30, 3 => 40, 4 => 50]; array_slice($numbers, 2); // [30, 40, 50] array_slice($numbers, 2, 2); // [30, 40] array_slice($numbers, -2); // [40, 50] array_slice($numbers, 0, 3); // [10, 20, 30] ?> ``` ### Combinando ```php 1, "b" => 2, "c" => 3] // Merge arrays array_merge($a, $b); // [0 => "a", 1 => "b", 2 => "c", 3 => 1, 4 => 2, 5 => 3] // For associative: later values overwrite earlier $x = ["a" => 1, "b" => 2]; $y = ["a" => 10, "c" => 3]; array_merge($x, $y); // ["a" => 10, "b" => 2, "c" => 3] ?> ``` ### Operador Spread (PHP 7.4+) ```php ``` ## Ordenando Arreglos ### Funciones de Ordenamiento ```php 25, "Bob" => 20, "Charlie" => 30]; asort($person); // Sort by value, keep keys arsort($person); // Sort by value descending ksort($person); // Sort by key krsort($person); // Sort by key descending ?> ``` ### Ordenamiento Personalizado ```php "Alice", "age" => 25], ["name" => "Bob", "age" => 20], ["name" => "Charlie", "age" => 30] ]; usort($people, function($a, $b) { return $a["age"] <=> $b["age"]; }); print_r($people); // Sorted by age ascending ?> ``` ### Reversa de Arreglo ```php ``` ## Filtrado y Mapeo ### array_filter() ```php $n % 2 === 0, ARRAY_FILTER_USE_KEY); // [1 => 2, 3 => 4, 5 => 6, 7 => 8, 9 => 10] // Both key and value $filtered = array_filter($numbers, function($value, $key) { return $value > 5 && $key < 8; }, ARRAY_FILTER_USE_BOTH); ?> ``` ### array_map() ```php $a + $b, [1, 2], [3, 4]); // [4, 6] // With keys preserved $indexed = array_map(fn($n) => $n * 2, $numbers); // Preserves original keys ?> ``` ### array_reduce() ```php $carry . " " . $item); // " Hello World PHP" ?> ``` ## Recorrido de Arreglos ### array_walk() ```php Apple, [1] => Banana, [2] => Cherry ?> ``` ## Funciones Útiles de Arreglos ### Verificando Todos/Cualquiera ```php $n % 2 === 0); // true // Any divisible by 3 $anyDiv3 = array_any($numbers, fn($n) => $n % 3 === 0); // false // PHP 7: use array_filter + count ?> ``` ### Fragmentación ```php [1, 2, 3], 1 => [4, 5, 6], 2 => [7]] ?> ``` ### Volteando ```php "apple", "b" => "banana"]; $flipped = array_flip($fruits); // ["apple" => "a", "banana" => "b"] // Useful for quick lookup $prices = ["apple" => 1.99, "banana" => 0.79]; $flippedPrices = array_flip($prices); // [1.99 => "apple", 0.79 => "banana"] ?> ``` ### Padding de Arreglo ```php ``` ### Suma y Producto ```php 1, "b" => 2, "c" => 3]; array_sum($assoc); // 6 ?> ``` ### Valores Únicos ```php ``` ### Rango ```php ``` ## Resumen - Arreglos: `$arr = [1, 2, 3]` o `array(1, 2, 3)` - Indexados: claves automáticas 0, 1, 2... - Asociativos: claves personalizadas `$arr = ["name" => "Alice"]` - Multidimensionales: arreglos dentro de arreglos - foreach para iteración: `foreach ($arr as $key => $value)` - `count()`, `sizeof()` para tamaño - `array_key_exists()`, `in_array()` para verificar - `array_keys()`, `array_values()` para extracción - `sort()`, `asort()`, `ksort()` para ordenar - `array_filter()`, `array_map()`, `array_reduce()` para transformación - `array_slice()`, `array_chunk()`, `array_merge()` para manipulación - Operador spread: `[...$a, ...$b]`

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →