Home Backend Development PHP Tutorial PHP array operation study notes_PHP tutorial

PHP array operation study notes_PHP tutorial

Jul 13, 2016 pm 05:15 PM
php getting Started study Summarize operate array of notes

Today, the editor will summarize some introductory learning notes for array operations in PHP, including: data creation, assignment, traversal, search, statistics, multi-dimensional arrays, etc. There are various array operations in PHP that you need to understand. Friends can refer to it.

What is an array?

An array is a collection of data, which is equivalent to a container. Data can be stored in this container according to certain rules. Equivalent to a hotel, there are many rooms in the hotel, and the rooms are numbered according to certain rules.

Array composition: The basic structure is as follows:

$array name (key) = value Array name: It is how one array is distinguished from another array, just like every hotel has a name.
Key: Also known as a pointer, index, or identifier. The key represents the location where a certain value is stored in the array, which is equivalent to the hotel's house number, and can be named in different ways. The corresponding value can be found by querying the key.
Value: The value is equivalent to what is stored in the room.

Assign value to create array

In PHP, there are two ways to create an array: variable assignment and function calling. Let’s talk about the former first.

Using the variable assignment method is very simple, just assign a value to an array variable directly.

Example:

The code is as follows Copy code
 代码如下 复制代码

$lang[]="php";
$lang[]="html";
$lang[]="css";
echo "$lang[0]
";
 echo "$lang[1]
";
 echo "$lang[2]
";
?>

$lang[]="php";

$lang[]="html";

$lang[]="css";

echo "$lang[0]
";

echo "$lang[1]
";

echo "$lang[2]
";

?>

Array contents generated by three assignment statements: 0=>php

1=>html

2=>css

Create array


In addition to the assignment to create an array introduced above, there is also a method to create an array by calling a function.
 代码如下 复制代码

$student=array("Tom","Jacky","Rose");
echo $student[0] ."t";
echo $student[1] ."t";
echo $student[2];
?>

php provides the array function to create an array. The basic structure is as follows: array (item1,item2... ,itemn)

/* item represents the element value in the array. The array() function automatically assigns identifiers to element values ​​when creating an array, increasing from 0 */

Example:

The code is as follows Copy code
$student=array("Tom","Jacky","Rose");

echo $student[0] ."t";

echo $student[1] ."t";

echo $student[2];

?>

 代码如下 复制代码
  $a=array(1 => "you",2 =>"are ", 5 =>"how ");
 echo $a[5];
 echo $a[2];
 echo $a[1];
?>
Array key name 1. Key name assignment When creating an array using the array() function, key names are automatically assigned to each value. In addition, we can also directly assign key names to elements according to our own needs. Basic structural form: array ( key => item ) Example 1:
The code is as follows Copy code
$a=array(1 => "you",2 =>"are ", 5 =>"how "); echo $a[5]; echo $a[2]; echo $a[1]; ?>

2. Use string as key name

Not only can you use integers as key names, you can also use strings as key names. Arrays that use strings as keys are called string-indexed arrays.

Example 2:

 代码如下 复制代码
$a=array("php"=>"动态网页","html"=>"静态网页","css"=>"网页排版");
 echo $a["php"] ."
";
 echo $a["html"] ."
";
 echo $a["css"];
?>

3. Modification of key names

Example 3:

The code is as follows Copy code
 代码如下 复制代码

$arr = array("a" => "新浪",   
   "b"=>"网易",    
   "c" => "腾讯", "雅虎"  
  );
  $arr[a] = "PHP中文社区";  
  $arr['e'] = "新浪";   
  $arr[] = "百度";    
 echo $arr['a'] ."
";   
 echo $arr['b'] ."
";   
 echo $arr['c'] ."
";   
 echo $arr['e'] ."
";   
 echo $arr[0] ."
";    
 echo $arr[1] ."
";    
?>

$arr = array("a" => "Sina",
"b"=>"NetEase",
"c" => "Tencent", "Yahoo"
);
$arr[a] = "PHP Chinese Community";
$arr['e'] = "Sina";
$arr[] = "Baidu";
echo $arr['a'] ."
";
echo $arr['b'] ."
";
echo $arr['c'] ."
";
echo $arr['e'] ."
";
echo $arr[0] ."
";
echo $arr[1] ."
";
?>

Create multi-dimensional array

When writing PHP programs, one-dimensional arrays sometimes cannot meet the needs. In this case, multi-dimensional arrays must be used. A multi-dimensional array is to add one or more subscripts to a one-dimensional array. The usage is roughly the same as that of a one-dimensional array, except that multi-dimensional data operations are more complex, but the function is more powerful.

Take a two-dimensional array as an example. It is like a small house inside a big house. The representation method is $a[0][0].

Example:
 代码如下 复制代码

 $a[0][0]=1;
 $a[0][1]=2;
 $a[0][2]=3;
 $a[1][0]=4;
 $a[1][1]=5;
 $a[1][2]=6;
 for($i=0;$i<=1;$i++){
  for($j=0;$j<=2;$j++){
   echo "$a[$i][$j]=" .$a[$i][$j] ."
"; /* "$"表示输出变量符号$ */
  }
 }
?>

The code is as follows Copy code

$a[0][0]=1;
$a[0][1]=2;
$a[0][2]=3;
$a[1][0]=4;
$a[1][1]=5;
$a[1][2]=6;
for($i=0;$i<=1;$i++){
for($j=0;$j<=2;$j++){
echo "$a[$i][$j]=" .$a[$i][$j] ."
"; /* "$" represents the output variable symbol $ */
}
}
?>

Output array

Outputting an array means displaying all element data of the array on the browser. How does PHP output an array? Commonly used PHP output array functions include var_dump() and print_r() functions.

1. The var_dump function recursively expands the array elements and displays the type, key name and element value of each element of the array.

 代码如下 复制代码
$a=array(0,5,array("php","html","css")); /* 创建一个嵌套的数组 */
var_dump($a);
?>
Example 1:

2. The print_r function value displays the key name and element value of the array element.

Example 2:

The code is as follows Copy code
 代码如下 复制代码


$b=array(1,2,3);
print_r($b);
?>

$b=array(1,2,3);

print_r($b);
?>

Test Array

Sometimes we don't know whether a variable is an array, we can use the is_array() function to test it.

Basic structural form:

is_array (variable)
 代码如下 复制代码

$a="apple iphone";
if(is_array($a)){
var_dump($a);
}
else echo "不是数组";
?>

Check whether the variable is an array, if so, return true, otherwise return false. Example:

The code is as follows Copy code

$a="apple iphone";

if(is_array($a)){

var_dump($a);

}
代码如下 复制代码


foreach ( array_expression as $value ) statement
/* array_expression是要遍历的数组
as作用是将数组的值赋给$value
statement是后续语句
*/
实例1:

$color=array('white' => '白色' ,
       'black' => '黑色' ,
       'red' => '红色' ,
       'green' => '绿色',
       'yellow' => '黄色');
 foreach( $color as $c) echo $c ."
";   
?>

else echo "Not an array";

?>

foreach traverses the array

When we use arrays, we often need to traverse the array and obtain each key or element value. PHP provides some functions specifically for traversing arrays. Here we first introduce the usage of foreach array traversal function.
 代码如下 复制代码

 foreach( $color as $c) echo $c ."
";
改为:


 foreach( $color as $key => $c) echo $key.$c ."
";

Structural form:
The code is as follows Copy code
foreach (array_expression as $value) statement /*array_expression is the array to be traversed The function of as is to assign the value of the array to $value Statement is the subsequent statement */ Example 1: 'white' , 'black' => 'black' , 'red' => 'red' , 'green' => 'green',         'yellow' => 'yellow'); foreach( $color as $c) echo $c ."
"; ?>
Not only the value of the element but also the key name can be obtained through foreach. The structural form: foreach (array_expression as $key => $value) statement Replace the code in line 7 in the above example:
The code is as follows Copy code
foreach( $color as $c) echo $c ."
"; Change to: foreach( $color as $key => $c) echo $key.$c ."
";


Find array element value

PHP can use array_search() to obtain the array key name. The structure is as follows:

array_search( $needle,$haystack )
/* The parameter $needle represents the value to be found */
/* $haystack represents the search object */
The array_search() function returns the key name, not the Boolean value, and returns false if it cannot be found. If the found element is exactly the first element, 0 is returned. PHP will automatically convert it to false, so you need to use "===" to determine the return value. ("===" determines whether they are congruent, details: PHP relational operators)

Example:

The code is as follows Copy code
 代码如下 复制代码

$s=array("a","b","c","d","e","f");
$i=array_search("a",$s); /* 查找数组是否有字符"a" */
if($i===false) /* 判断查找结果 */
echo "在数组s中找不到字符'a'";
else echo "输出数组$s的键名:" .$i; /* 输出键名 */
?>

$s=array("a","b","c","d","e","f"); $i=array_search("a",$s); /* Find whether the array contains the character "a" */ if($i===false) /* Determine the search results */

echo "Character 'a' not found in array s";

else echo "Output the key name of array $s:" .$i; /* Output key name */

?>

 代码如下 复制代码


 count ( $var,$mode )
/* $var参数$var通常是一个数组,函数返回var中的单元数目 */
/* mode是可选参数 */
实例:

$a=array("peple","man","women");
$b=count($a); /* 统计数组元素个数 */
echo $b;
?>

Calculate the number of array elements

Arrays can also be operated like variables. For example, when we need PHP to count the number of array elements, we can use the count() function to calculate the number of elements in the array.

Structural form:

The code is as follows Copy code

count ( $var, $mode )

/* $var parameter $var is usually an array, and the function returns the number of cells in var */

/* mode is an optional parameter */

Example:

$a=array("peple","man","women");

代码如下 复制代码
$languages=array(
'c'=>'php',
  'd'=>'asp',
  'a'=>'jsp',
  'b'=>'java'
 );
 krsort($languages);
 foreach($languages as $key=>$val){
  echo "$key = $val".'
';
 };
?>

$b=count($a); /* Count the number of array elements */

echo $b; ?>

Array sort

php provides a series of array sorting functions, we can sort the array as needed. There are three main ways to sort arrays:

Sort by key value
 代码如下 复制代码
  asort($languages);
 print_r($languages);
 echo "
";
 rsort($languages);
 print_r($languages);
That is, the order is based on the size of the identifier ASCⅡ code value. ksort(): Sort by array identifier order krsort(): Sort array identifier in reverse order Example 1:
The code is as follows Copy code
$languages=array(<🎜> 'c'=>'php', 'd'=>'asp', 'a'=>'jsp', 'b'=>'java' ); krsort($languages); foreach($languages ​​as $key=>$val){ echo "$key = $val".'
'; }; ?>
Sort by element value asort(): Sort the array from small to large; rsort(): Sort the array in reverse order from large to small. Change lines 8-11 of Example 1 to:
The code is as follows Copy code
asort($languages); print_r($languages); echo "
"; rsort($languages); print_r($languages);

Delete the original key name sorting

sort(): Sort the array from small to large;
rsort(): Sort the array in reverse order from large to small.
Change lines 8-11 of Example 2 to:

Array operators

The code is as follows
 代码如下 复制代码

sort($languages);
 foreach($languages as $key=>$val){
  echo "languages[$key] = $val".'
';
 };

 

Copy code

sort($languages); foreach($languages ​​as $key=>$val){

echo "languages[$key] = $val".'
';

};
 代码如下 复制代码
$a=array(
'a'=>'php',
   'b'=>'html',
   'c'=>'css'
 );
 $b=array(
   'a'=>'asp',
   'b'=>'jsp'
 );
 $c=$a+$b; /* 合并数组 */
 var_dump($c);
 echo "
";
 $c=$b+$a; /* 调换顺序合并数组 */
 var_dump($c); 
?>

 代码如下 复制代码
$a=array('php','asp');
$b=array(1=>'asp',0=>'php');
 var_dump($a==$b);
 var_dump($a===$b);
?>

数组运算符
例子 名称 结果
$a + $b 联合 $a 和 $b 的联合。
$a == $b 相等 如果 $a 和 $b 具有相同的键/值对则为 TRUE
$a === $b 全等 如果 $a 和 $b 具有相同的键/值对并且顺序和类型都相同则为 TRUE
$a != $b 不等 如果 $a 不等于 $b 则为 TRUE
$a <> $b 不等 如果 $a 不等于 $b 则为 TRUE
$a !== $b 不全等 如果 $a 不全等于 $b 则为 TRUE
Merge array calculation example:
The code is as follows Copy code
$a=array(<🎜> 'a'=>'php', 'b'=>'html', 'c'=>'css' ); $b=array( 'a'=>'asp', 'b'=>'jsp' ); $c=$a+$b; /* merge arrays */ var_dump($c); echo "
"; $c=$b+$a; /* Replace the order and merge the arrays */ var_dump($c); ?> Array comparison example:
The code is as follows Copy code
$a=array('php','asp');<🎜> $b=array(1=>'asp',0=>'php'); var_dump($a==$b); var_dump($a===$b); ?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628836.htmlTechArticleThe editor will summarize some introductory learning notes for array operations in PHP today, including: data creation, Assignment, traversal, search, statistics, multi-dimensional arrays, etc. various array operations in php...
Array operator
Examples Name Results
$a + $b United Union of $a and $b.
$a == $b Equal TRUE if $a and $b have the same key/value pair.
$a === $b Congruent TRUE if $a and $b have the same key/value pairs and are of the same order and type.
$a != $b Not equal TRUE if $a is not equal to $b.
$a <> $b Not equal TRUE if $a is not equal to $b.
$a !== $b Not congruent TRUE if $a is not exactly equal to $b.
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,

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

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

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