search
HomeBackend DevelopmentPHP TutorialPHP Array Introduction to arrays and array functions_PHP tutorial

PHP Array Introduction to arrays and array functions_PHP tutorial

Jul 20, 2016 am 11:02 AM
arrayphpandfunctionEncyclopediaTutorialarrayIntroductionconduct

php tutorial array introduction to arrays and array functions
The array function allows you to operate on arrays.

php supports single-dimensional and multi-dimensional arrays. At the same time, a function is provided to construct an array using the database tutorial query results.
Install
array functions are an integral part of php core. No installation is required to use these functions.
php array function
php: Indicates the earliest php version that supports this function.

PHP’s array is actually an associative array, or a hash table. PHP does not need to declare the size of the array in advance, and can create the array by direct assignment. For example:
//The most traditional, use numbers as keys and assign values ​​
$state[0]="beijing";
$state[1]="hebei";
$state[2]="tianjin";
//If the key is an increasing number, you can omit
$city[]="shanghai";
$city[]="tianjin";
$city[]="guangzhou";
//Use string as key
$capital["china"]="beijing";
$capital["japan"]="tokyo";
It is more convenient to create an array with array(). You can pass array elements to it as array parameters, or you can use the => operator to create an associative array. For example:
$p=array(1,3,5,7);
$capital=array(“china”=>”beijing”, “japan=>”tokyo”);
Array is actually a grammatical structure, not a function. Similar to array, there is also list(), which can be used to extract values ​​from an array and assign values ​​to multiple variables. For example:
list($s,$t)=$city;
echo $s,' ',$t;
Output result:shanghai tianjin
Note that the list method can only be used with arrays indexed by numbers.
PHP has built-in some commonly used array processing functions, please refer to the manual for details. Examples of commonly used functions are as follows, count or sizeof can get the length of an array, array_merge can merge two or more arrays, and array_push (pop) can use arrays like a stack.
Copy the code The code is as follows:
$state[0]="beijing";
$state[1]="hebei";
$state[2]="tianjin";
$city[]="shanghai";
$city[]="tianjin";
$city[]="guangzhou";
$capital["china"]="beijing";
$capital["japan"]="tokyo";
echo count($city),'
';
array_push($capital,"paris");
$newarray=array_merge($city,$capital);
foreach($newarray as $elem)
echo $elem.'
';
?>

The output result is:
3
shanghai
tianjin
guangzhou
beijing
tokyo
paris


p

Function Description php
array() creates an array. 3
array_change_key_case() returns an array whose keys are all uppercase or lowercase. 4
array_chunk() splits an array into new array chunks. 4
array_combine() creates a new array by merging two arrays. 5
array_count_values() is used to count the number of occurrences of all values ​​in an array. 4
array_diff() returns the difference array of two arrays. 4
array_diff_assoc() compares the key name and key value and returns the difference array of the two arrays. 4
array_diff_key() compares key names and returns an array of differences between the two arrays. 5
array_diff_uassoc() calculates the difference of an array by doing an index check using a user-provided callback function. 5
array_diff_ukey() uses the callback function to compare the key names to calculate the difference of the array. 5
array_fill() fills an array with the given values. 4
array_filter() uses a callback function to filter elements in an array. 4
array_flip() swaps keys and values ​​in an array. 4
array_intersect() calculates the intersection of arrays. 4
array_intersect_assoc() compares key names and key values ​​and returns the intersection array of the two arrays. 4
array_intersect_key() Computes the intersection of arrays using key name comparison. 5
array_intersect_uassoc() calculates the intersection of arrays with index checking and compares the indices with a callback function. 5
array_intersect_ukey() uses a callback function to compare key names to calculate the intersection of arrays. 5
array_key_exists() checks whether the given key name or index exists in the array. 4
array_keys() returns all keys in the array. 4
array_map() applies a callback function to the cells of the given array. 4
array_merge() Merges one or more arrays into a single array. 4
array_merge_recursive() Merges one or more arrays recursively. 4
array_multisort() Sorts multiple arrays or multidimensional arrays. 4
array_pad() pads an array with values ​​to the specified length. 4
array_pop() pops (pops) the last element of the array. 4
array_product() calculates the product of all values ​​in an array. 5
array_push() pushes one or more cells (elements) to the end of the array (push). 4
array_rand() randomly selects one or more elements from an array and returns it. 4
array_reduce() uses a callback function to iteratively reduce an array to a single value. 4
array_reverse() reverses the order of elements in the original array, creates a new array and returns it. 4
array_search() searches the array for a given value and returns the corresponding key if successful. 4
array_shift() deletes the first element in the array and returns the value of the deleted element. 4
array_slice() removes a segment of value from the array based on conditions and returns it. 4
array_splice() removes a portion of an array and replaces it with another value. 4
array_sum() calculates the sum of all values ​​in an array. 4
array_udiff() uses a callback function to compare data to calculate the difference of arrays. 5
array_udiff_assoc() calculates the difference of an array with index checking and compares the data using a callback function. 5
array_udiff_uassoc() calculates the difference set of the array with index checking, using a callback function to compare the data and index. 5
array_uintersect() calculates the intersection of arrays and uses callback functions to compare data. 5
array_uintersect_assoc() calculates the intersection of arrays with index checking and compares data using callback functions. 5
array_uintersect_uassoc() calculates the intersection of arrays with index checking, using a callback function to compare the data and index. 5
array_unique() removes duplicate values ​​from an array. 4
array_unshift() inserts one or more elements at the beginning of the array. 4
array_values() returns all values ​​in the array. 4
array_walk() applies a user function to each member of the array. 3
array_walk_recursive() recursively applies a user function to each member of an array. 5
arsort() sorts an array in reverse order and maintains index relationships. 3
asort() sorts an array and maintains index relationships. 3
compact() creates an array including variable names and their values. 4
count() counts the number of elements in an array or the number of attributes in an object. 3
current() returns the current element in the array. 3
each() returns the current key/value pair in the array and moves the array pointer forward one step. 3
end() sets the array's internal pointer to the last element. 3
extract() imports variables from an array into the current symbol table. 3
in_array() checks whether the specified value exists in the array. 4
key() gets the key name from an associative array. 3
krsort() sorts the array in reverse order by key name. 3
ksort() sorts the array by key name. 3
list() assigns the values ​​in an array to some variables. 3
natcasesort() sorts an array in a case-insensitive manner using the "natural sort" algorithm. 4
natsort() sorts an array using the "natural sorting" algorithm. 4
next() moves the internal pointer in the array forward one position. 3
pos() Alias ​​for current(). 3
prev() rolls back the array's internal pointer one bit. 3
range() creates an array containing elements in the specified range. 3
reset() sets the array's internal pointer to the first element. 3
rsort() sorts an array in reverse order. 3
shuffle() rearranges the elements in the array in random order. 3
sizeof() Alias ​​for count(). 3
sort() sorts an array. 3
uasort() sorts the values ​​in an array using a user-defined comparison function and maintains index association. 3
uksort() sorts the keys in an array using a user-defined comparison function. 3
usort() sorts the values ​​in an array using a user-defined comparison function. 3
php array constant
php: Indicates the earliest php version that supports this constant.

Constant Description php
case_lower is used in array_change_key_case() to convert array key names to lowercase letters.
case_upper is used in array_change_key_case() to convert array key names to uppercase letters.
sort_asc is used in the array_multisort() function to sort in ascending order.
sort_desc is used in the array_multisort() function to sort items in descending order.
sort_regular is used for general comparison of objects.
sort_numeric is used to perform numerical comparisons of objects.
sort_string is used for string comparison of objects.
sort_locale_string Performs a string comparison of objects based on the current locale. 4
count_normal
count_recursive
extr_overwrite
extr_skip
extr_prefix_same 
extr_prefix_all
extr_prefix_invalid
extr_prefix_if_exists
extr_if_exists 
extr_refs


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445370.htmlTechArticlephp tutorial array Introduction to arrays and array functions The array function allows you to operate on arrays. PHP supports single-dimensional and multi-dimensional arrays. It also provides database tutorial query results to construct...
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's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment