Introduction aux tableaux en PHP

L'article suivant, Arrays in PHP, vous donne un aperçu de la création de tableaux en PHP. Un tableau est une collection de types de données similaires. Un tableau stocke plusieurs valeurs dans une seule variable. Pourquoi un tableau est-il nécessaire alors que le travail de stockage d'une valeur peut également être effectué par variable? La réponse est parce que stocker des valeurs de données limitées comme le nombre de nombres 5 est possible, mais lorsque le nombre augmente pour dire 100 ou 200, nous devons stocker 100 valeurs dans 100 variables, ce qui est un peu difficile, donc nous les stockons dans un tableau. C'est pourquoi les tableaux sont utilisés.

Comment créer des tableaux en PHP?

Syntaxe:
variablename = array();
OU
variablename(i) = value;,

Où nom de variable est le nom de la variable i est la clé ou la valeur d'index est la valeur de l'élément.

Exemple de création d'un tableau

$colors = array(“Red”, ”Green”, ”Blue”);
Pour calculer la longueur du tableau, nous utilisons le mot clé count.
$length = count($colors); // output is 3

Chaque valeur du tableau est appelée comme un élément du tableau. L'index du tableau commence par 0. Et l'indice du dernier élément d'un tableau est la longueur totale du tableau moins 1.

Dans l'exemple donné ci-dessus, l'index de Rouge est 0, Vert est 1 et celui de Bleu est 2. Il devient vraiment plus facile d'accéder au tableau à l'aide de l'index ou d'une clé. Pour obtenir la valeur à chaque index d'un tableau, nous parcourons le tableau donné. Pour boucler le tableau, nous utilisons une boucle foreach ou une boucle.

Comment fonctionne le tableau en PHP?

Des boucles comme foreach et for sont utilisées pour parcourir le tableau. Chaque tableau a des index de départ à partir de 0 et ainsi de suite:

Types de tableaux en PHP

Il existe 3 types de tableau en PHP, apprenons chaque type de tableau en détail:

  1. Tableau numérique ou indexé.
  2. Tableau associatif.
  3. Tableau multidimensionnel.

1. Tableau numérique

Ce type de tableau où un index est toujours un nombre ne peut pas être une chaîne. Il peut stocker n'importe quel nombre d'éléments et également tout type d'éléments.

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

Code:

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

Production:

OU

L'autre façon de déclarer le tableau numérique est selon le programme suivant. Dans ce programme, nous verrons également à modifier et à imprimer la valeur.

Code:

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

Production:

Nous allons maintenant apprendre à utiliser la boucle for pour parcourir un tableau

Code:

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

Production:

2. Tableau associatif

Ce tableau se présente sous la forme d'une paire clé-valeur, où la clé est l'index du tableau et la valeur est l'élément du tableau.

Syntaxe:

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

OU

L'autre façon de déclarer un tableau associatif sans mot-clé tableau

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

Code:

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

Production:

3. Tableau multidimensionnel

Ce tableau est un tableau de tableau où la valeur de tableau contient un tableau.

Syntaxe:

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

Code:

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

Production:

OU

Tableau multidimensionnel dans un tableau associatif

Code:

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

Production:

Méthodes de tableau en PHP

Voici les méthodes de Array en PHP:

1. Méthode Count ()

Cette méthode est utilisée pour compter le nombre d'éléments dans un tableau.

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

Code:

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

Production:

3

2. Méthode Array_walk ()

Cette méthode prend deux paramètres en entrée, le premier paramètre est le tableau d'entrée, le deuxième paramètre est le nom de la fonction déclarée. Cette méthode est utilisée pour parcourir chaque élément du tableau.

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

Code:

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

Production:

e – anglais h –Hindi m –Marathi

3. Méthode In_array ()

Cette méthode effectue une recherche sur le tableau, que le tableau donné contienne ou non une valeur particulière. S'il est trouvé ou non, il exécutera le bloc if, else respectif

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

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

Production:

Maths trouvés dans le tableau donné

4. Méthode Array_pop ()

Cette méthode supprime le dernier élément du tableau donné.

Syntaxe array_pop(array_name)

Code:

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

Production:

5. Méthode Array_push ()

Cette méthode ajoute des éléments donnés à la fin du tableau.

Syntaxe:

array_push(array_name, value1, value2, …)

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

Production:

6. Méthode Array_shift ()

Cette méthode supprime et renvoie le premier élément du tableau.

Syntaxe: array_shift(array_name)

Code:

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

Production:

7. Méthode Array_unshift ()

Cette méthode insère des éléments donnés au début du tableau.

Syntaxe:

array_unshift(array_name, value1, value2, …)

Code:

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

Production:

8. Méthode Array_reverse ()

Cette méthode est utilisée pour inverser les éléments du tableau.

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

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

Production:

Conclusion

Cet article couvre tous les niveaux de concepts simples et complexes des tableaux de rubriques en PHP. J'espère que vous avez trouvé cet article intéressant et informatif à des fins d'apprentissage.

Articles recommandés

Cela a été un guide pour les tableaux en PHP. Nous discutons ici comment créer des tableaux en PHP ?, Comment fonctionnent les tableaux en PHP?, 3 types et 8 méthodes de tableau en PHP avec la syntaxe, le code et la sortie appropriés. Vous pouvez également consulter nos autres articles suggérés pour en savoir plus-

  1. Tableaux en R
  2. Qu'est-ce que PHP?
  3. Avantages de PHP
  4. Introduction à PHP
  5. Différents types de boucles avec ses avantages
  6. Tableau multidimensionnel en PHP