Home  >  Article  >  Backend Development  >  PHP array operation study notes_PHP tutorial

PHP array operation study notes_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:15:30847browse

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:
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