search
HomeBackend DevelopmentPHP TutorialIntroduction to Arrays_PHP Tutorial

Introduction to Arrays_PHP Tutorial

Jul 13, 2016 pm 05:45 PM
phpintroducelandfastsupplydataarraymethodyesOverviewofRelatedprogrammingmanage

Array

1. Overview

Arrays provide a quick and convenient way to manage a group of related data and are an important part of PHP programming. Through arrays, a large amount of data of the same nature can be stored, sorted, inserted and deleted, etc., which can effectively improve the efficiency of program development and improve the way programs are written.

An array is a collection of data. The data is organized according to certain rules to form an operable whole. It is one of the means to effectively organize and manage a large amount of data. A large amount of data of the same nature can be stored through the array function. Sorting, inserting and deleting operations can effectively improve program development efficiency and improve the way programs are written.

2.Array type

The essence of an array is to store, manage and operate a set of variables. In PHP, arrays are divided into one-dimensional arrays, two-dimensional arrays and multi-dimensional arrays. However, whether it is one-dimensional or multi-dimensional, arrays can be uniformly divided into two types: numerical index arrays and associative arrays. Numeric index arrays use numbers as key names, and association arrays use numbers as key names. Arrays use strings as keys.


Numeric index array, the subscript (key name) consists of numbers, starting from 0 by default. Each number corresponds to the position of the array element in the array. There is no need to specify it. PHP will automatically assign an integer value to the key name of the numerical index array. Then it automatically increments from this value, or you can specify the position to start from.

Associative array, the subscript (key name) is an array composed of a mixture of numeric values ​​and strings.

Arrays require key names to access the values ​​stored in the array.


3. Declare array
Note: 1. The array name starts with $, the first character is a letter or underscore, followed by any number of letters, numbers or underscores.
2. In the same program, scalar variables and array variables cannot have the same name.
3. The name of the array is case-sensitive

There are two ways to declare an array, namely user declaration and function declaration.

1. User Statement
$array['0']="php array";
$array['1']="php learning";

2. Function declaration
$arrr=array('one'='php','two'='java');

Create a two-dimensional array. What is created above has only one column of data content, so it is called a one-dimensional array. If two one-dimensional arrays are combined into one array, it is a two-dimensional array.
Example: $str=array(
"Network"=>array("ip address","gateway");
"Book"=>array("Spring and Autumn","Warring States");
)


4. Traverse the array
Traversing an array means accessing each element in the array in a certain order until all elements are accessed. In PHP, arrays can be traversed through process statements (foreach and for loop statements) and functions (list() and each()).

foreach(),
To traverse an array, you need to use the count() function to get the number. If the array to be traversed is a numeric index array, and the index value of the array is a continuous integer, you can use a for loop to traverse, but the prerequisite is that you need to apply the count() function to obtain the number of elements in the array, and then use the obtained The number of elements is used as the execution condition of the for loop to complete the array loop.
Example: for($i=0;$i"}

Traverse the array through the array functions list and each:

The list() function assigns the values ​​in the array to some variables. This function can only be used for numerically indexed arrays, and the numerical index starts from 0. Syntax: void list(mixed...) The parameter mixed is the name of the variable to be assigned.
The each() function returns the key name and corresponding value in the array, and moves the array pointer forward. Syntax: array each (array array) The parameter array is the input array.
Example: Use the list function to obtain the value of the array returned in the each function, and assign it to $name and $value respectively, and then use a while loop to output
while(list($name,$value)=each($array)){echo $name=$value}
5. Output array elements
The print_r() function can output the structure of the array, or the var_dump() function can be used to output the array structure.
The echo statement simply outputs an element in the array, and must have an identifier and an array index in the format echo $array[0]. Similarly, the print statement can also output an element in the array.

6.php array function
Array functions that are commonly used in development.

The count() function can count the number of elements in the array
The array_push() function adds elements to an array. Appends the passed element to the end of an array and returns the total number of new elements in the array. Syntax: array_push($array,"New Element 1","New Element 2")
The array_pop function can get and return the last element in the array, and reduce the length of the array by 1. If the array is empty (or not an array), it will return null

Remove duplicate elements from an array:
The array_unique() function can delete duplicate elements in the array
Use unset() to delete an element in an array. unset($arr_int[1]);

Get the key name of the specified element in the array: Obtaining the key name of the specified element in the array is mainly achieved through array functions.

array_search() is used to obtain the key name of the specified element in the array, search for the given value in the array, and return the key name after finding it, otherwise return FALSE, distinguishing between upper and lower case letters
array_search(orange, $arr[is case sensitive])

Use the array_keys() function to get all the key names of repeated elements in the array

The conversion of strings and arrays is essential and is mainly implemented using the explode and implode functions.
explode
Implode converts array elements into string type

7.php global array

Using the PHP global array, you can obtain a large amount of environment-related information, such as the current user session, user operating environment, local operating environment, etc.

$_SERVER[] global array to obtain information about server and client configuration and current request
The $_GET[] and $POST[] global arrays are used to receive the data passed to the current page by the GET and POST methods respectively.
$_COOKIE[] global array stores information passed to the script through http cookies
$_ENV[] is used to provide server-related information
$_REQUEST[] can be used to obtain the information passed to the script by GET, POST and http cookies.
$_SESSION[] is used to obtain information about session variables
$_FILES[] is a special array, which will be explained in detail later


Review:

1.Array overview
2. Array type 2 types
3. Declare array User creation and function creation, one-dimensional array, two-dimensional array
4. Traverse and output arrays foreach and for and the functions list() and each() to traverse multi-dimensional arrays. The output includes var_dump, print_r, echo $ss[1]
5.php array function counts array elements, adds elements to the array, gets the last element in the array, deletes duplicate elements in the array, and gets the key name of the specified element in the array
6.php global arrays Which ones are commonly used

Author "Technology is King"

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478634.htmlTechArticleArray 1. Overview Arrays provide a quick and convenient way to manage a group of related data and are php programs important content in design. Arrays can be used to process a large amount of data of the same nature...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools