Home Backend Development PHP Tutorial PHP learning array courseware

PHP learning array courseware

Dec 19, 2016 pm 01:36 PM
php

Subscript: The identification name in the array, which is the code name of the string or integer in the array.

The number of index values ​​​​in the array is called a several-dimensional array.
Index value: An index is a structure that sorts the values ​​of one or more columns in a database table.

Array Classification
Arrays in PHP are divided into two types:
Indexed array: The indexed index value is an integer, starting with 0. Indexed arrays are used when identifying things by position.
Associative array: Associative (associative) association uses a string as the index value, the index value is the column name, and is used to access the column data.

Arrays usually use assignment
Generally, there are two ways to assign arrays:
$a[1]="dsadsadsa";
$b[2]="dsadsadsad";
Use the array function:
$a= array("dsads","dsadsa",321312);
One-dimensional array: When the array has only one index value (subscript), it is called a one-dimensional array.
Format of direct array assignment:
$Array variable name [index value] = data content;
Note: The index value can be a string or an integer, but 1 and "1" are different. One of them belongs to an integer and the other to a string. .

Arrays with the same name without index values ​​are arranged in order.
Example:
$a=array(1,2,3,4,5,6);
$b=array("one", "two", "three");
$c= Array (0 = & gt; "aaa", 1 = & gt; "bbb", 2 = & gt; "ccc");
$ d = array ("aaa", 6 = & gt; "bbb", "ccc");
$e=array("name"=>"zhang", "age"=>20);
?>
Two-dimensional array
Format of multi-dimensional array:
$a[0][]="dsadas ";
$a[0][]="dsadsa"; This group is 1 and 2 under the 0 index value under $a
If the array function is used to declare the format as follows:
$a=array("dsadsa"," dsadas",21,array("dsadsa","dsadas"));

Array traversal
foreach loop structure:
foreach only uses two formats: array loop
foreach(array_exprssion(array expression) as $value) ;
foreach(array_exprssion(array expression) as $key=>$value);
The first format traverses the given array_exprssion array. Each time through the loop the current value is assigned to my $calue and the pointer inside the array moves forward one step.
The second format does the same thing, except that the key value of the current cell will also be assigned to the variable $key in each loop.
When foreach starts executing, the pointer inside the array will automatically point to the first unit. Also note that foreach operates on a copy of the specified array, not the array itself
$arr=array(10,20,30,40,50,60);
foreach($arr as $k=>$v ){
echo "$k=>$v
";
}

Output result: 0=>10 1=>20 2=>30 3=>40 4=>50 5 =>60//Subscript=>Integer
Combining list(), each() and while loop
each():
$arr=array(1,2,3,4,5);
$a =each($arr);
print_r($a);
Output result: Array ( [1] => 1 [value] => 1 [0] => 0 [key] => 0 )
Get the first value of the array value subscript key
list():
$arr3=array("a","b","c");
list($key,$value)=each($arr3 );

echo $key."
".$value;
Output result: 0 a List() can be said to assign values ​​to a set of variables in one step. It can only be used for numerically indexed arrays and assumes numerical indexing Start from 0 .
while loop
$arr=array(1,2,3,4,5,6,7,8,9,);
while(list($key,$value)=each($arr)){
$ key++;
                                                     $key."Output result: 1=>1 2=>2 3=>3 4=>4 5=>5 6=>6 7=>7 8=>8 9=>9
reset ()Array pointer redirection
After executing each(), the array pointer will stay at the next unit in the array or at the last unit when the end of the array is reached.
is_array detects whether the variable is an array true and returns true false false
$arr=array(1,2,3,4,5,6,"saas");
while(list($k,$v) = each($ arr))
{
if(is_array($arr))
{
$x += $v;
echo $x;
}
else
{
$x += $k;
}
}
This example It cannot fully reflect the function of is_array, but it can be used as a reference.
Array pointer
next(): responsible for moving the pointer backward
prve(): responsible for moving the pointer forward
end(): will point the pointer to the last element of the array
reset(): unconditionally move the current pointer to The first index position
Syntax format: mixed next(array name)
$arr=(array(1,2,3,4,5));
echo end($arr);
Output result: 5
key( ), current() and count()
key() function is to read the index value of the data pointed to by the current pointer.
The current() function reads the content data of the data pointed to by the current pointer. The
count() function is used to count the number of all elements in the array, which means that the function will return the length value of the target array.
Format: int count (array name);

key(): Get the key name from the associative array
$array = array('fruit1' => 'apple','fruit2' => 'orange',' fruit3' => 'grape','fruit4' => 'apple','fruit5' => 'apple');
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'
';
}
next($array);
}
Output result: fruit1, fruit4, fruit5

current(): return array The current unit in
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport); // $mode = ' foot';
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
Pay attention to the example to return the current value in the array Unit

count(): Calculate the number of units in the array
$arr=array(1,2,3,4,5,6);
echo count($arr);
Output result: 6

array_change_key_case( )
array_change_key_case returns an array whose string key names are all lowercase or uppercase
It contains two morphological functions [CASE_UPPER] to convert to uppercase, and [CAS_LOWER] to convert to lowercase.
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
Output result: Array ( [FIRST] => 1 [SECOND ] => 4)

 array_chunk()
array_chunk() sub-function will decompose the data content of the target array into several small arrays with the specified number of indexes and include them in the original array.
$arr=array(1,2,3,4,5,6);
$a=array_chunk($arr,3);
print_r($a);
Output result: Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [1] => Array ( [0] => 4 [1] =>5 array_count_values ​​(target array)
The result value returned by this function will be expressed in the form of an array using the content data of the original array as an index.
$arr=array(1,2,3,3,2,6);
print_r(array_count_values($arr));
Output result: Array ( [1] => 1 [2] => 2 [ 3] => 2 [6] => 1 )

array_fill
array_fill allows users to customize values ​​to fill the specified index section in the target array.
Syntax format: array_fill (starting index position, section size, specified character)
The starting index position and section size must be integer (integer) values, and the section size specified must not be 0.
$a = array_fill(5, 6, 'banana');
print_r($a);
Output result: Array([5] => banana[6] => banana[7] => banana[ 8] => banana[9] => banana[10] => banana)

array_filter
array_filter passes each value in the target array to the user-defined function in turn. If the user-defined function returns TRUE (true
), the current value of the input array will be included in the returned result array. The key names of the array remain unchanged.
Syntax format: array_filter (target array, user-defined function)
function odd($var)
{
return($var % 2 == 1);
}
$array1 = array("a"=> 1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
print_r(array_filter($array1, "odd"));
Output result: Odd:Array([a] => 1[c] => 3[e] => 5)
$entry = array(0 => 'foo',1 => false,2 => -1,3 => null,4 => '');
print_r(array_filter($entry));
Output result Array([0] =>foo[2] => -1 )
Other callback functions: array_walk (), array_map()

array_flip
array_flip inverts the index and content value in the target array. The inverted array will use the original content value as the index, and the index As data content.
array_flip syntax format: exchange keys and values ​​in the array
array_flip (target array)
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
Output content: Array([1] =>b[2] =>c)
If the same value appears multiple times , the last key name will be used as its value, and all others are lost.

​ array_sum
array_sum is used to calculate the sum of all element values ​​in the array.
Syntax format: array_sum (target array)

array_unique
array_unique is used to remove duplicate data in the target array and return new values ​​after operation.

​ array_keys and array_values ​​
array_keys This function will ignore the original key name and re-index the array using sequential numbers, for associative arrays.
array_values ​​This function returns a key array containing numbers or strings. Returns all values ​​in the input array and numerically indexes them.
$arr=array("a"=>1,"b"=>2,"abc",2);
$b=array_keys($arr);
$c=array_values($arr);
Output result: $b=Array ([0] => a [1] => b [2] => 0 [3] => 1 )
$c=Array ( [0] => 1 [1] => 2 [2] => abc [3] => 2)

Retrieval of array
Retrieval of array mainly refers to judging the key name or element value of the array to determine a certain The presence or absence of array elements.
Grammar format: bool in_array(mixed $needle, array $haystack[, bool $strict]);
$arr3=array(1,2,3,"hello","wprld");
$b=in_array(" hell",$arr3,true);
var_dump($b);
$arr4=array(1,2,3,array("hello","world"));
$b=in_array(array("hello ","world"),$arr4);
var_dump($b);
Output result: bool(false) bool(true)

Conversion between arrays and variables
extract() and compact() functions perform array and Convert between variables.
After conversion, the key name of the array element and the variable name, as well as the value of the element and the value of the variable maintain a corresponding relationship.
extract This function is used to pour variables from the array into the current symbol table
$info = array("user_id"=>2006001,"user_name"=>"Tong Xiangyu", "position"=>"Project Manager ");
extract($info);
echo $user_id;
Output result: 2006001
compact() accepts a variable number of parameters. Each parameter can be a string containing a variable name or an array containing a variable name. The array can also contain other arrays whose unit contents are variable names. compact() can be processed recursively.
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array("city","state");
$result = compact("event", "nothing_here",$location_vars);
print_r($result);
Output result: Array ( [event] => SIGGRAPH [city] => San Francisco [state] => CA )

Array and stack
The array_push() function pushes one or more elements onto the end of the array stack (push) and returns the number of elements pushed onto the stack. The
array_pop() function pops the last element of the array stack and returns the element.
Example array_push
$a=array("dsa","dsas","dfs","gfd");
array_push($a,"ssss","ddddd");
print_r($a);
Output Result: Array ( [0] => dsa [1] => dsas [2] => dfs [3] => gfd [4] => ssss [5] => ddddd )
Example array_pop Pops and returns the last element of array and decrements the length of array by one. If array is empty (or not an array) NULL will be returned.
$a=array("dsa","dsas","dfs","gfd");
array_pop($a);
print_r($a);
Output result: Array ( [0] => dsa [1] => dsas [2] => dfs )

Arrays and Columns
A queue can also appear in the form of an array. The first element in the array is the head, and the last element is the tail.
You can use the stack method to insert elements at the end of the pair.
To delete the opposite element from the queue array, you can use the array_shift function, which shifts the first element of the array out and returns it as the result. At the same time, the length of the array is reduced by 1, and other elements are moved forward one bit. All numeric key names will be changed to count from zero, and text key names will not change.
array_shift example
$a=array("dsa","dsas","dfs","gfd");
$title=array_shift($a);
print_r($a);
Output result: Array ( [ 0] => dsas [1] => dfs [2] => gfd )
You can use the array_unshift() function to insert one or more elements at the beginning of the queue array. This function returns the number of successfully inserted elements.
$a=array("dsa","dsas","dfs","gfd");
$title=array_unshift($a,"a",array(1,2));
print_r($a) ;
Output result: Array ( [0] => a [1] => Array ( [0] => 1 [1] => 2 ) [2] => dsa [3] => dsas [4] => dfs [5] => gfd )
It can be seen from the results that you can also insert the array

Sorting of the array
Ignore the array sorting of the key name
sort() positive
rsort() inverted
usort ()
$arr = array("3"=>"lemon", "2"=>"orange", "4"=>"banana", "1"=>"apple");
ksort($arr);
foreach ($arr as $key => $val) {
“echo “$key = $valn”;
}

Calculation of Array
Calculations on arrays are more convenient. The simplest calculation is to find the sum of all elements inside an array. You can also treat arrays as a set, merge two or more arrays, calculate the difference or intersection between arrays, etc.
Merge of arrays Merge is not +
Example
$arr2=array(1,2,3);
$arr3=array(3,4,5);
$a=array_merge($arr2,$arr3);
print_r($a);
Output result: Array ([0] => 1 [1] => 2 [2] => 3 [3] => 3 [4] => 4 [5] => 5)
Calculate the difference set of arrays
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" = > "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
Output result: Array ([1] => blue) Difference The level is to take the previous difference value
to calculate the intersection of the arrays
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => " green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
Output result: Array ( [a] => green [0] => ; red ) The intersection takes the

common to both upper and lower sides to create an array of the specified range:
range();
Remove duplicate values ​​in the array:
array_unique();
Return the array in reverse order:
array_reverse();

Random function of array: Random number
srand((float) microtime()*10000000) Set the random generator seed
array_rand();
array_shuffle();
Example
echo date("Ymd").rand(1000000,9999999 )."jpg";

Output result: 200805096246795jpg's random number

The above is the content of the PHP array learning courseware. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles