Tableaux en PHP

王林
Libérer: 2024-08-29 12:42:53
original
489 Les gens l'ont consulté

L'article suivant, Arrays in PHP, fournit 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 stockage d’une valeur peut également être effectué par une 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 jusqu'à, disons, 100 ou 200, nous devons stocker 100 valeurs dans 100 variables, ce qui est un peu difficile ; ainsi, nous le stockons dans un tableau. C'est pourquoi des tableaux sont utilisés.

PUBLICITÉ Cours populaire dans cette catégorie DEVELOPPEUR PHP - Spécialisation | Série de 8 cours | 3 tests simulés

Commencez votre cours de développement de logiciels libres

Développement Web, langages de programmation, tests de logiciels et autres

Comment créer des tableaux en PHP ?

Syntaxe :

variablename = array();
Copier après la connexion

OU

variablename[i] = value;
Copier après la connexion

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

Exemple pour créer un tableau

$colors = array("Red","Green","Blue");
Copier après la connexion

Pour calculer la longueur du tableau, nous utilisons le mot-clé count.

$length = count($colors); // output is 3
Copier après la connexion

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

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

Comment fonctionne le tableau en PHP ?

Les boucles comme for each 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 trois types de tableaux 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

Dans ce type de tableau, où un index est toujours un nombre, il ne peut pas s'agir d'une chaîne. Au lieu de cela, il peut stocker n'importe quel nombre d'éléments et n'importe quel type d'élément.

Syntaxe :

variable name = array("value1","value2","value3","value4")
Copier après la connexion

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);
?>
Copier après la connexion

Sortie :

Tableaux en PHP

OU

L'autre façon de déclarer le tableau numérique est 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]."<br>"; // will give Kiwi
//To modify Orange value
$input[1] = "Mango";
// Now echo $input[1] will give Mango
echo $input[1]."<br>"; // Mango
//To print the array we can use
print_r($input);
?>
Copier après la connexion

Sortie :

Tableaux en PHP

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<count($input); $i++) {
echo $input[$i];
echo "<br>";
}
?>
Copier après la connexion

Sortie :

Tableaux en PHP

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");
Copier après la connexion

OU

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

$input[$key1] = $value1;
$input[$key2] = $value2;
$input[$key3] = $value3;
$input[$key4] = $value4;
Copier après la connexion

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."<br>";}
?>
Copier après la connexion

Sortie :

Tableaux en PHP

3. Tableau multidimensionnel

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

Syntaxe :

$input =array(
array('value1', 'value2', 'value3'),
array('value4', 'value5', 'value6'),
array('value7', 'value8', 'value9'));,
Copier après la connexion

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 .'--'. "<br>";
foreach($value as $k=>$v)
{echo $v ." ";}
echo "<br>";
}
?>
Copier après la connexion

Sortie :

Tableaux en PHP

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 "<br>";
// foreach to loop the inner array
foreach($book as $key=>$value)
{
echo $key." ". $value. "<br>";}
}?>
Copier après la connexion

Sortie :

Tableaux en PHP

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)
Copier après la connexion

là où le décompte est obligatoire, le mode est facultatif.

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);
?>
Copier après la connexion

Sortie :

Tableaux en PHP

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 et 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...)
Copier après la connexion

où le tableau est requis function_name est requis

le paramètre est facultatif

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");
?>
Copier après la connexion

Output:

Tableaux en PHP

3. In_array() method

This method performs a search on the array, whether the given array contains a particular value or not. If found or not found, it will execute respective if, else block

Syntax:

in_array(search_value, array_name)
Copier après la connexion

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";
}
?>
Copier après la connexion

Output:

Tableaux en PHP

4. Array_pop() method

This method removes the last element from the given array.

Syntax

array_pop(array_name)
Copier après la connexion

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);
?>
Copier après la connexion

Output:

Tableaux en PHP

5. Array_push() method

This method adds given elements at the end of the array.

Syntax:

array_push(array_name, value1, value2, ...)
Copier après la connexion

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);
?>
Copier après la connexion

Output:

Tableaux en PHP

6. Array_shift() method

This method removes and returns the first element of the array.

Syntax: 

array_shift(array_name)
Copier après la connexion

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);
?>
Copier après la connexion

Output:

Tableaux en PHP

7. Array_unshift() method

This method inserts given elements into the beginning of the array.

Syntax:

array_unshift(array_name, value1, value2,…)
Copier après la connexion

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);
?>
Copier après la connexion

Output:

Tableaux en PHP

8. Array_reverse() method

This method is used to reverse the elements of the array.

Syntax:

array_reverse(array_name, preserve)
Copier après la connexion

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));
?>
Copier après la connexion

Output:

Tableaux en PHP

Conclusion

This article covers all levels of concepts, simple and complex, of the topic arrays in PHP. I hope you found this article interesting and informative for the learning purpose.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
php
source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!