Introducción a las matrices en PHP

El siguiente artículo, Arrays in PHP, le proporciona un esquema para la creación de arrays en PHP. Una matriz es una colección de tipos de datos similares. Una matriz almacena múltiples valores en una sola variable. ¿Por qué existe la necesidad de una matriz cuando el trabajo de almacenar un valor también se puede hacer por variable? La respuesta es porque es posible almacenar valores de datos limitados como el recuento de números 5, pero cuando el recuento aumenta para decir 100 o 200, necesitamos almacenar 100 valores en 100 variables, lo cual es un poco difícil, por lo que lo almacenamos en una matriz. Es por eso que se utilizan matrices.

¿Cómo crear matrices en PHP?

Sintaxis:
variablename = array();
O
variablename(i) = value;,

Donde nombre de variable es el nombre de la variable i es la clave o el valor del índice es el valor del elemento.

Ejemplo para crear una matriz

$colors = array(“Red”, ”Green”, ”Blue”);
Para calcular la longitud de la matriz usamos la palabra clave count.
$length = count($colors); // output is 3

Cada valor en la matriz se denomina como un elemento de la matriz. El índice de la matriz comienza con 0. Y el índice del último elemento en una matriz es la longitud total de la matriz menos 1.

En el ejemplo anterior, el índice de Red es 0, Green es 1 y el de Blue es 2. Realmente se hace más fácil acceder a la matriz con la ayuda del índice o una tecla. Para obtener el valor en cada índice de una matriz, recorremos la matriz dada. Para recorrer la matriz, usamos un bucle foreach o para un bucle.

¿Cómo funciona la matriz en PHP?

Los bucles como foreach y for se usan para recorrer la matriz. Cada matriz tiene índices iniciales desde 0 y así sucesivamente:

Tipos de matrices en PHP

Hay 3 tipos de matriz en PHP. Aprendamos cada tipo de matriz en detalle:

  1. Matriz numérica o indexada.
  2. Matriz asociativa.
  3. Matriz multidimensional.

1. Matriz numérica

Este tipo de matriz donde un índice siempre es un número, no puede ser una cadena. Puede almacenar cualquier número de elementos y también cualquier tipo de elementos.

Sintaxis:
variable name = array(“value1”, ”value2”, ”value3”, ”value4”)

Código:

<_?php
//Example to demonstrate numeric array
$input = array("Apple", "Orange", "Banana", "Kiwi");
//Here, to get these values we will write like
echo $input(0) . "\n"; // will give Apple
echo $input(1) . "\n"; // will give Orange
echo $input(2) . "\n"; // will give Banana
echo $input(3) . "\n"; // will give Kiwi
// To get the length of array we will use count
echo "The count of the array is " . count($input); // will give 4
echo "\n";
//To print the array we can use
print_r($input);
?>

Salida:

O

La otra forma de declarar la matriz numérica es según el siguiente programa. En este programa, también veremos cómo modificar e imprimir el valor.

Código:

<_?php
//Example to demonstrate numeric array in another way
$input(0) = "Apple";
$input(1) = "Orange";
$input(2) = "Banana";
$input(3) = "Kiwi";
// To get Kiwi we will write like
echo $input(3)."
"; // will give Kiwi
//To modify Orange value
$input(1) = "Mango";
// Now echo $input(1) will give Mango
echo $input(1)."
"; // Mango
//To print the array we can use
print_r($input);
?>

Salida:

Ahora aprenderemos cómo usar el bucle for para atravesar una matriz

Código:

<_?php
//Example to demonstrate for loop on a numeric array
//declaring the array
$input = array("Apple", "Orange", "Banana", "Kiwi", "Mango");
//the for loop to traverse through the input array
for($i=0;$i echo $input($i);
echo "
";
)
?>
//Example to demonstrate for loop on a numeric array
//declaring the array
$input = array("Apple", "Orange", "Banana", "Kiwi", "Mango");
//the for loop to traverse through the input array
for($i=0;$i echo $input($i);
echo "
";
)
?>

Salida:

2. Matriz asociativa

Esta matriz tiene la forma de un par clave-valor, donde la clave es el índice de la matriz y el valor es el elemento de la matriz.

Sintaxis:

$input = array(“key1”=>”value1”,
“key2”=>”value2”,
“key3”=>”value3”,
“key4”=>”value4”);

O

La otra forma de declarar una matriz asociativa sin palabra clave de matriz

$input($key1) = $value1;
$input($key2) = $value2;
$input($key3) = $value3;
$input($key4) = $value4;

Código:

?php
//Example to demonstrate associative array
//declaring an array
$input = array(
"Jan"=>31,
"Feb"=>28,
"Mar"=>31,
"Apr"=>30);
// the for loop to traverse through the input array
foreach($input as $in) (
echo $in."
";)
?>

Salida:

3. Matriz multidimensional

Esta matriz es una matriz de matriz donde el valor de matriz contiene una matriz.

Sintaxis:

$input =array(
array('value1', 'value2', 'value3'),
array('value4', 'value5', 'value6'),
array('value7', 'value8', 'value9'));,

Código:

<_?php
//Example to demonstrate multidimensional array
// declaring a multidimensional array
$input = array ("colors"=>array ("Red", "Green", "Blue"),
"fruits"=>array ("Apple", "Orange", "Grapes"),
"cars"=>array ("Skoda", "BMW", "Mercedes")
);
//the foreach loop to traverse through the input array
foreach($input as $key=>$value) (
echo $key .'--'. "
";
foreach($value as $k=>$v)
(echo $v ." ";)
echo "
";
)
?>

Salida:

O

Matriz multidimensional en una matriz asociativa

Código:

<_?php
//Example to demonstrate multidimensional array
// declaring a multidimensional array
$input = array(
"The_Alchemist" => array (
"author" => "Paulo Coelho",
"type" => "Fiction",
"published_year" => 1988),
"Managing_Oneself" => array(
"author" => "Peter Drucker",
"type" => "Non-fiction",
"published_year" => 1999
), "Measuring_the_World" => array(
"author" => "Daniel Kehlmann",
"type" => "Fiction",
"published_year" => 2005
));
//the foreach loop to traverse through the input array
//foreach to loop the outer array
foreach($input as $book) (
echo "
";
// foreach to loop the inner array
foreach($book as $key=>$value)
(
echo $key." ". $value. "
";)
)?>

Salida:

Métodos de matriz en PHP

A continuación se muestran los métodos de Array en PHP:

1. Método Count ()

Este método se utiliza para contar el número de elementos en una matriz.

Sintaxis: Count(array, mode) where the count is required mode is optional.

Código:

<_?php
//Example to demonstrate use of in_array method
//declaring associative array
$input=array('English', 'Hindi', 'Marathi');
//counting the number of elements in the given array
echo count($input);
?>

Salida:

3

2. Método Array_walk ()

Este método toma dos parámetros como entrada, el primer parámetro es la matriz de entrada, el segundo parámetro es el nombre de la función declarada. Este método se utiliza para recorrer cada elemento de la matriz.

Sintaxis:
array_walk(array, function_name, parameter…)
where array is required, function_name is required
parameter is optional

Código:

<_?php
//Example to demonstrate use of array_walk method
//creating a function to print the key and values of the given array
function fun($val, $k) (
echo $k. " --" .$val ."\n";
)
// declaring associative array
$input=array("e"=>'English', "h"=>'Hindi', "m"=>'Marathi');
//passing this array as a first parameter to the function
// array_walk,
//second paramter as the name of the function being called
array_walk($input, "fun");
?>

Salida:

e – Inglés h –Hindi m –Marathi

3. Método In_array ()

Este método realiza una búsqueda en la matriz, ya sea que la matriz dada contenga un valor particular o no. Si se encuentra o no, se ejecutará respectivamente si, de lo contrario, bloqueará

Sintaxis:
in_array(search_value, array_name)
Where both the parameters are required

Código:
<_?php
//Example to demonstrate use of in_array method
// declaring associative array
$input=array('English', 'Hindi', 'Marathi', "Maths", "Social Science");
// using in_array to find Maths in given array
if(in_array("Maths", $input)) (
echo "Found Maths in the given array";
)
else
(
echo "Did not find Maths in the given array";
)
?>

Salida:

Matemáticas encontradas en la matriz dada

4. Método Array_pop ()

Este método elimina el último elemento de la matriz dada.

Sintaxis array_pop(array_name)

Código:

<_?php
//Example to demonstrate use of array_pop method
// declaring array
$input=array('English', 'Hindi', 'Marathi');
// before using array_pop on the given array
print_r($input);
// after using array_pop method on the given array
array_pop($input);
echo "\n ";
print_r($input);
?>

Salida:

5. Método Array_push ()

Este método agrega elementos dados al final de la matriz.

Sintaxis:

array_push(array_name, value1, value2, …)

Código:
<_?php
//Example to demonstrate use of array_push method
// declaring array
$input=array('English', 'Hindi', 'Marathi');
// before using array_push on the given array
print_r($input);
// after using array_push method on the given array
array_push($input, "Economics", "Maths", "Social Science");
echo "\n";
//printing the array
print_r($input);
?>

Salida:

6. Método Array_shift ()

Este método elimina y devuelve el primer elemento de la matriz.

Sintaxis: array_shift(array_name)

Código:

<_?php
//Example to demonstrate use of array_push method
// declaring array
$input=array('English', 'Hindi', 'Marathi');
// before using array_shift on the given array
print_r($input);
echo "\n";
// after using array_shift method on the given array
echo array_shift($input);
?>

Salida:

7. Método Array_unshift ()

Este método inserta elementos dados al comienzo de la matriz.

Sintaxis:

array_unshift(array_name, value1, value2, …)

Código:

<_?php
//Example to demonstrate use of array_push method
// declaring array
$input=array('English', 'Hindi', 'Marathi');
// before using array_unshift on the given arrayprint_r($input);
echo "\n";
// after using array_unshift method on the given array
array_unshift($input, "Economics");
print_r($input);
?>

Salida:

8. Método Array_reverse ()

Este método se usa para invertir los elementos de la matriz.

Sintaxis:
array_reverse(array_name, preserve)
where array_name is required,
preserve is optional

Código:
<_?php
//Example to demonstrate use of in_array method
// declaring associative array
$input=array("e"=>'English', "h"=>'Hindi', "m"=>'Marathi');
// array before reversing the elements
print_r($input);
echo "\n";
// printing the reverse
// array after reversing the elements
print_r(array_reverse($input));
?>

Salida:

Conclusión

Este artículo cubre todos los niveles de conceptos simples y complejos de las matrices de temas en PHP. Espero que hayas encontrado este artículo interesante e informativo para el propósito de aprendizaje.

Artículos recomendados

Esta ha sido una guía de matrices en PHP. Aquí discutimos cómo crear matrices en PHP ?, ¿Cómo funcionan las matrices en PHP ?, 3 tipos y 8 métodos de matrices en PHP con sintaxis, código y salida apropiados. También puede consultar nuestros otros artículos sugeridos para obtener más información.

  1. Arreglos en R
  2. ¿Qué es PHP?
  3. Ventajas de PHP
  4. Introducción a PHP
  5. Diferentes tipos de bucles con sus ventajas
  6. Matriz multidimensional en PHP