Arrays in PHP

王林
Freigeben: 2024-08-29 12:42:53
Original
475 Leute haben es durchsucht

Der folgende Artikel, Arrays in PHP, bietet eine Übersicht zum Erstellen von Arrays in PHP. Ein Array ist eine Sammlung ähnlicher Datentypen. Ein Array speichert mehrere Werte in einer einzigen Variablen. Warum ist ein Array erforderlich, wenn die Speicherung eines Werts auch durch eine Variable erfolgen kann? Die Antwort liegt darin, dass es möglich ist, Werte begrenzter Daten wie die Anzahl der Zahlen 5 zu speichern, aber wenn die Anzahl beispielsweise auf 100 oder 200 ansteigt, müssen wir 100 Werte in 100 Variablen speichern, was etwas schwierig ist; Daher speichern wir es in einem Array. Aus diesem Grund werden Arrays verwendet.

WERBUNG Beliebter Kurs in dieser Kategorie PHP-ENTWICKLER - Spezialisierung | 8-Kurs-Reihe | 3 Probetests

Starten Sie Ihren kostenlosen Softwareentwicklungskurs

Webentwicklung, Programmiersprachen, Softwaretests und andere

Wie erstelle ich Arrays in PHP?

Syntax:

variablename = array();
Nach dem Login kopieren

ODER

variablename[i] = value;
Nach dem Login kopieren

Wobei der Variablenname der Name der Variablen ist, i der Schlüssel ist, oder der Indexwert der Elementwert ist.

Beispiel zum Erstellen eines Arrays

$colors = array("Red","Green","Blue");
Nach dem Login kopieren

Um die Länge des Arrays zu berechnen, verwenden wir das Schlüsselwort count.

$length = count($colors); // output is 3
Nach dem Login kopieren

Jeder Wert im Array wird als Element des Arrays bezeichnet. Der Array-Index beginnt mit 0. Und der Index des letzten Elements in einem Array ist die Gesamtlänge des Arrays minus 1.

Im obigen Beispiel ist der Index von Rot 0, Grün ist 1 und Blau ist 2. Dadurch wird der Zugriff auf das Array mithilfe des Index oder einer Taste einfacher. Um den Wert an jedem Index eines Arrays zu erhalten, durchlaufen wir das angegebene Array. Um das Array zu durchlaufen, verwenden wir eine foreach-Schleife oder eine for-Schleife.

Wie funktioniert das Array in PHP?

Schleifen wie for every und for werden verwendet, um das Array zu durchlaufen. Jedes Array hat Startindizes von 0 und so weiter:

Arten von Arrays in PHP

Es gibt drei Arten von Arrays in PHP; Lassen Sie uns jeden Array-Typ im Detail lernen:

  1. Numerisches oder indiziertes Array
  2. Assoziatives Array
  3. Mehrdimensionales Array
1. Numerisches Array

In diesem Array-Typ, bei dem ein Index immer eine Zahl ist, kann er kein String sein. Stattdessen kann es eine beliebige Anzahl von Elementen und jeden Elementtyp speichern.

Syntax:

variable name = array("value1","value2","value3","value4")
Nach dem Login kopieren

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);
?>
Nach dem Login kopieren

Ausgabe:

Arrays in PHP

ODER

Die andere Möglichkeit, das numerische Array zu deklarieren, ist das folgende Programm. In diesem Programm werden wir uns auch um das Ändern und Drucken von Werten kümmern.

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);
?>
Nach dem Login kopieren

Ausgabe:

Arrays in PHP

Jetzt lernen wir, wie man die for-Schleife verwendet, um ein Array zu durchlaufen

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>";
}
?>
Nach dem Login kopieren

Ausgabe:

Arrays in PHP

2. Assoziatives Array

Dieses Array hat die Form eines Schlüssel-Wert-Paares, wobei der Schlüssel der Index des Arrays und der Wert das Element des Arrays ist.

Syntax:

$input = array("key1"=>"value1",
"key2"=>"value2",
"key3"=>"value3",
"key4"=>"value4");
Nach dem Login kopieren

ODER

Die andere Möglichkeit, ein assoziatives Array ohne ein Array-Schlüsselwort zu deklarieren

$input[$key1] = $value1;
$input[$key2] = $value2;
$input[$key3] = $value3;
$input[$key4] = $value4;
Nach dem Login kopieren

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>";}
?>
Nach dem Login kopieren

Ausgabe:

Arrays in PHP

3. Mehrdimensionales Array

Dieses Array ist ein Array des Arrays, wobei der Wert des Arrays ein Array enthält.

Syntax:

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

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>";
}
?>
Nach dem Login kopieren

Ausgabe:

Arrays in PHP

ODER

Mehrdimensionales Array in einem assoziativen Array

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>";}
}?>
Nach dem Login kopieren

Ausgabe:

Arrays in PHP

Array-Methoden in PHP

Unten sind die Methoden von Array in PHP:

1. Count()-Methode

Diese Methode wird verwendet, um die Anzahl der Elemente in einem Array zu zählen.

Syntax:

Count(array, mode)
Nach dem Login kopieren

Wo die Zählung erforderlich ist, ist der Modus 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);
?>
Nach dem Login kopieren

Ausgabe:

Arrays in PHP

2. Array_walk()-Methode

Diese Methode benötigt zwei Parameter als Eingabe; Der erste Parameter ist das Eingabearray und der zweite Parameter ist der Name der deklarierten Funktion. Diese Methode wird verwendet, um jedes Element im Array zu durchlaufen.

Syntax:

array_walk(array, function_name, parameter...)
Nach dem Login kopieren

wobei ein Array erforderlich ist, Funktionsname ist erforderlich

Parameter ist 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");
?>
Nach dem Login kopieren

Output:

Arrays in 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)
Nach dem Login kopieren

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";
}
?>
Nach dem Login kopieren

Output:

Arrays in PHP

4. Array_pop() method

This method removes the last element from the given array.

Syntax

array_pop(array_name)
Nach dem Login kopieren

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);
?>
Nach dem Login kopieren

Output:

Arrays in PHP

5. Array_push() method

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

Syntax:

array_push(array_name, value1, value2, ...)
Nach dem Login kopieren

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);
?>
Nach dem Login kopieren

Output:

Arrays in PHP

6. Array_shift() method

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

Syntax: 

array_shift(array_name)
Nach dem Login kopieren

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);
?>
Nach dem Login kopieren

Output:

Arrays in PHP

7. Array_unshift() method

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

Syntax:

array_unshift(array_name, value1, value2,…)
Nach dem Login kopieren

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);
?>
Nach dem Login kopieren

Output:

Arrays in PHP

8. Array_reverse() method

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

Syntax:

array_reverse(array_name, preserve)
Nach dem Login kopieren

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));
?>
Nach dem Login kopieren

Output:

Arrays in 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.

Das obige ist der detaillierte Inhalt vonArrays in PHP. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
php
Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!