Introduzione alle matrici in PHP

Il seguente articolo, Array in PHP, fornisce uno schema per la creazione di array in PHP. Un array è una raccolta di tipi di dati simili. Un array memorizza più valori in una singola variabile. Perché è necessario un array quando il lavoro di memorizzazione di un valore può essere svolto anche da variabili? La risposta è perché è possibile memorizzare valori di dati limitati come il conteggio dei numeri 5, ma quando il conteggio aumenta per dire 100 o 200 dobbiamo memorizzare 100 valori in 100 variabili, il che è un po 'difficile, quindi lo memorizziamo in un array. Questo è il motivo per cui vengono utilizzate le matrici.

Come creare array in PHP?

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

Dove nome variabile è il nome della variabile i è la chiave o il valore dell'indice è il valore dell'elemento.

Esempio per creare una matrice

$colors = array(“Red”, ”Green”, ”Blue”);
Per calcolare la lunghezza dell'array utilizziamo la parola chiave count.
$length = count($colors); // output is 3

Ogni valore nella matrice è definito come un elemento della matrice. L'indice dell'array inizia con 0. E l'indice dell'ultimo elemento in un array è la lunghezza totale dell'array meno 1.

Nell'esempio sopra riportato, l'indice di rosso è 0, il verde è 1 e quello di blu è 2. Diventa davvero più facile accedere all'array con l'aiuto dell'indice o di una chiave. Per ottenere il valore in ciascun indice di un array, eseguiamo il ciclo attraverso l'array specificato. Per eseguire il loop dell'array utilizziamo un loop foreach o per un loop.

Come funziona l'array in PHP?

I loop come foreach e for vengono utilizzati per eseguire il loop nell'array. Ogni array ha indici iniziali da 0 e così via:

Tipi di array in PHP

Esistono 3 tipi di array in PHP per imparare dettagliatamente ogni tipo di array:

  1. Matrice numerica o indicizzata.
  2. Matrice associativa.
  3. Matrice multidimensionale.

1. Matrice numerica

Questo tipo di array in cui un indice è sempre un numero non può essere una stringa. Può memorizzare qualsiasi numero di elementi e anche qualsiasi tipo di elementi.

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

Codice:

<_?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);
?>

Produzione:

O

L'altro modo per dichiarare l'array numerico è secondo il seguente programma. In questo programma, vedremo anche modificare e stampare il valore.

Codice:

<_?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);
?>

Produzione:

Ora impareremo come usare il ciclo for per attraversare un array

Codice:

<_?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 "
";
)
?>

Produzione:

2. Matrice associativa

Questo array ha la forma di una coppia chiave-valore, dove la chiave è l'indice dell'array e il valore è l'elemento dell'array.

Sintassi:

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

O

L'altro modo per dichiarare un array associativo senza parola chiave array

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

Codice:

?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."
";)
?>

Produzione:

3. Matrice multidimensionale

Questo array è un array di array in cui il valore di array contiene un array.

Sintassi:

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

Codice:

<_?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 "
";
)
?>

Produzione:

O

Matrice multidimensionale in una matrice associativa

Codice:

<_?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. "
";)
)?>

Produzione:

Metodi di array in PHP

Di seguito sono riportati i metodi di array in PHP:

1. Metodo Count ()

Questo metodo viene utilizzato per contare il numero di elementi in un array.

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

Codice:

<_?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);
?>

Produzione:

3

2. Metodo Array_walk ()

Questo metodo accetta due parametri come input, il primo è l'array di input, il secondo è il nome della funzione dichiarata. Questo metodo viene utilizzato per eseguire il ciclo attraverso ciascun elemento dell'array.

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

Codice:

<_?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");
?>

Produzione:

e – inglese h –hindi m –Marathi

3. Metodo In_array ()

Questo metodo esegue una ricerca sull'array, indipendentemente dal fatto che l'array specificato contenga un valore particolare o meno. Se trovato o non trovato, eseguirà il rispettivo blocco if, else

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

Codice:
<_?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";
)
?>

Produzione:

Trovato matematica nell'array specificato

4. Metodo Array_pop ()

Questo metodo rimuove l'ultimo elemento dall'array specificato.

Sintassi array_pop(array_name)

Codice:

<_?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);
?>

Produzione:

5. Metodo Array_push ()

Questo metodo aggiunge determinati elementi alla fine dell'array.

Sintassi:

array_push(array_name, value1, value2, …)

Codice:
<_?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);
?>

Produzione:

6. Metodo Array_shift ()

Questo metodo rimuove e restituisce il primo elemento dell'array.

Sintassi: array_shift(array_name)

Codice:

<_?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);
?>

Produzione:

7. Metodo Array_unshift ()

Questo metodo inserisce gli elementi dati all'inizio dell'array.

Sintassi:

array_unshift(array_name, value1, value2, …)

Codice:

<_?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);
?>

Produzione:

8. Metodo Array_reverse ()

Questo metodo viene utilizzato per invertire gli elementi dell'array.

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

Codice:
<_?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));
?>

Produzione:

Conclusione

Questo articolo copre tutti i livelli di concetti semplici e complessi degli argomenti trattati in PHP. Spero che tu abbia trovato questo articolo interessante e informativo ai fini dell'apprendimento.

Articoli consigliati

Questa è stata una guida agli array in PHP. Qui discutiamo come creare array in PHP ?, Come funzionano gli array in PHP ?, 3 tipi e 8 metodi di array in PHP con sintassi, codice e output appropriati. Puoi anche consultare i nostri altri articoli suggeriti per saperne di più-

  1. Matrici in R
  2. Che cos'è PHP?
  3. Vantaggi di PHP
  4. Introduzione a PHP
  5. Diversi tipi di loop con i suoi vantaggi
  6. Matrice multidimensionale in PHP

Categoria: