HOWTO · PHP

Inizializza array vuoto in PHP

Questo articolo introduce come inizializzare un array vuoto in PHP. Include parentesi quadre e la funzione array().

In questa pagina

Questo articolo introdurrà diversi metodi per inizializzare un array vuoto in PHP.

Usa le parentesi quadre [] per inizializzare un array vuoto in PHP

In PHP, abbiamo più metodi e funzioni per inizializzare un array vuoto. Possiamo usare le parentesi quadre [] per inizializzare l’array. La sintassi corretta per utilizzare le parentesi quadre è la seguente.

$arrayName = [];

La sintassi precedente creerà un array vuoto. Possiamo anche aggiungere elementi a questo array usando parentesi quadre. Il programma seguente mostra il modo in cui possiamo usare le parentesi quadre [] per inizializzare un array vuoto in PHP.

<?php
$myarray = [];
echo("This is an empty array.\n");
var_dump($myarray);
?>

Produzione:

This is an empty array.
array(0) {
}

Possiamo anche usare [] per aggiungere elementi all’array.

<?php
$myarray = [];
echo("This is an empty array.\n");
var_dump($myarray);
$myarray = [
    0=> "Sara",
    1=> "John",
    2=> "Melissa",
    3=> "Tom",
];
echo("Now the array has four elements.\n");
var_dump($myarray);
?>

Produzione:

This is an empty array.
array(0) {
}
Now the array has four elements.
array(4) {
  [0]=>
  string(4) "Sara"
  [1]=>
  string(4) "John"
  [2]=>
  string(7) "Melissa"
  [3]=>
  string(3) "Tom"
}

Usa la funzione array() per inizializzare un array vuoto in PHP

Possiamo anche usare la funzione array() per inizializzare un array vuoto in PHP. Questa funzione è una funzione specializzata per la creazione di un array. La sintassi corretta per utilizzare questa funzione è la seguente.

array($index1=>$value1, $index2=>$value2, ...,$indexN=>$valueN);

La funzione array ha N parametri. N è il numero di elementi che l’array avrà. I dettagli dei suoi parametri sono i seguenti.

Variabili Descrizione
$index1, $index2, …, $indexN È l’indice degli elementi dell’array. Può essere un numero intero o una stringa.
$value1, $value2, …, $valueN È il valore degli elementi dell’array.

Il programma sotto mostra il modo in cui possiamo usare la funzione array() per inizializzare un array vuoto in PHP.

<?php
$myarray = array();
echo("This is an empty array.\n");
var_dump($myarray);
?>

Produzione:

This is an empty array.
array(0) {
}

Allo stesso modo, possiamo usare questo operatore per scrivere N stringhe multilinea.

<?php
$myarray = array();
echo("This is an empty array.\n");
var_dump($myarray);
$myarray = array(
    0=> "Sara",
    1=> "John",
    2=> "Melissa",
    3=> "Tom",
);
echo("Now the array has four elements.\n");
var_dump($myarray);
?>

Produzione:

This is an empty array.
array(0) {
}
Now the array has four elements.
array(4) {
  [0]=>
  string(4) "Sara"
  [1]=>
  string(4) "John"
  [2]=>
  string(7) "Melissa"
  [3]=>
  string(3) "Tom"
}