Trova l'indice Foreach in PHP
-
Usa la variabile
keyper trovare l’indice Foreach in PHP -
Usa la variabile
indexper trovare l’indice Foreach in PHP -
Usa sia la
keyche la variabileindexper trovare l’indiceforeachin PHP
In questo articolo, introdurremo metodi per trovare l’indice foreach.
- Utilizzando la variabile
key - Utilizzando la variabile
index - Usando sia la variabile
keyche quellaindex
Usa la variabile key per trovare l’indice Foreach in PHP
La chiave della variabile memorizza l’indice di ogni valore nel bucle foreach. Il bucle foreach in PHP viene utilizzato come segue.
foreach($arrayName as $value){
//code
}
Il valore della variabile memorizza il valore di ogni elemento dell’array.
<?php
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach ($array as $key => $value) {
echo "The index is = " . $key . ", and value is = ". $value;
echo "\n";
}
?>
La variabile chiave qui contiene l’indice del bucle foreach. Il valore della variabile mostra il valore di ogni elemento in array.
Produzione:
The index is = 0, and the value is = 1
The index is = 1, and the value is = 2
The index is = 2, and the value is = 3
The index is = 3, and the value is = 4
The index is = 4, and the value is = 5
The index is = 5, and the value is = 6
The index is = 6, and the value is = 7
The index is = 7, and the value is = 8
The index is = 8, and the value is = 9
The index is = 9, and the value is = 10
Usa la variabile index per trovare l’indice Foreach in PHP
La variabile index viene utilizzata come variabile aggiuntiva per mostrare l’indice di foreach in ogni iterazione.
<?php
// Declare an array
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$index = 0;
foreach($arr as $key=>$val) {
echo "The index is $index";
$index++;
echo "\n";
}
?>
Produzione:
The index is 0
The index is 1
The index is 2
The index is 3
The index is 4
The index is 5
The index is 6
The index is 7
The index is 8
The index is 9
Usa sia la key che la variabile index per trovare l’indice foreach in PHP
Ora, useremo sia la variabile chiave che un’ulteriore variabile index per trovare l’indice di foreach.
<?php
// Declare an array
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$index = 0;
foreach ($arr as $key=>$value) {
echo "The index is $index";
$index = $key+1;
echo "\n";
}
?>
Abbiamo memorizzato il valore della variabile chiave con un incremento del suo valore nella variabile indice. In questo modo, possiamo trovare l’indice di foreach utilizzando sia la variabile chiave che la variabile indice.
Produzione:
The index is 0
The index is 1
The index is 2
The index is 3
The index is 4
The index is 5
The index is 6
The index is 7
The index is 8
The index is 9