About PHP (vi) arrays

Source: Internet
Author: User
Tags file upload http post

An overview of arrays

1.1 Arrays are compound types

1.2 Arrays can store any length of data, or you can store any type of data


ii. type of array

2.1 Indexed array: Subscript is an ordinal integer as an index

<?php
	$user [0] = 1;
	$user [1] = "Zhangsan";
	$user [2] = "aaa@bb.com";
	
	Echo ' <pre> ';
	Print_r ($user);
	Echo ' </pre> ';
? >

2.2 Associative array: Subscript is a string as an index

<?php
	$user ["id"] = 1;
	$user ["name"] = "Zhangsan";
	$user ["email"] = "aaa@bb.com";
	
	Echo ' <pre> ';
	Print_r ($user);
	Echo ' </pre> ';
	$user ["name"] = "Lisi";
	echo $user ["name"];
? >

three, multiple declarations of the array of ways

3.1 Assigning values directly to array elements

A. If the index subscript does not give a value, the index will start sequentially from 0
B. If an index subscript is given, the next one will be 1 from the maximum start

C. If the preceding subscript appears, if it is assigned, the previous element is assigned a value
D. Mixed declarations, indexes and associations do not affect each other (without affecting the declaration of index subscript)


3.2 using the array () function

A. The default is an indexed array

B. If you specify a subscript for an associative array and an indexed array, use the key => value
C. Use the "," split before multiple members

<?php
	$user 1 = array (1, "Zhsangsan", "Nan", "aaa@bbb.com");
	Echo ' <pre> ';
	Print_r ($user 1);
	Echo ' </pre> ';
	
	/**
	 Array (
	    [0] => 1
	    [1] => Zhsangsan
	    [2] =>
	    [3] => nan
	    [4] => AAA@BBB.COM
  )
	 *
	
	/$user 2 = array ("id" =>1, "name" => "Zhsangsan", "Age" =>10, 100=> "Nan", "aaa@bbb.com");
	Echo ' <pre> ';
	Print_r ($user 2);
	Echo ' </pre> ';
	
	/**
	 Array (
	    [id] => 1
	    [name] => Zhsangsan
	    [age] => [
	    MB] => nan
	    [[] => aaa@bbb.com
	 )
	 * * *
?>

Important knowledge points: two-dimensional arrays

<?php
	$info =array (
		"User" =>array (
				Array (1, "Zansan", "Nan"),
				Array (2, "Lisi", "NV")
		 )
	);
	echo $info ["User"][1][1]; Lisi
	Echo ' <pre> ';
	Print_r ($info);
	Echo ' </pre> ';
	
	/**
	 	Array ([
		    user] => array ([
		            0] => array
		                (
		                    [0] => 1
		                    [1] => Zansan
		                    [2] =>
		                    [3] => nan
		                )
		
		            [1] => Array
		                (
		                    [0] => 2
		                    [1] => Lisi
		                    [2] =>
		                    [3] => nv))
		
		        */
?>

four, the array of traversal

4.1 Looping through using a For statement (not recommended)

Limitations: The array must be an indexed array, and the subscript must be contiguous (however the index array subscript can be discontinuous and the array may be an associative array)

<?php
  	$user = Array (1, "Zhasna", "aaa@bb.com");
	for ($i = 0; $i < count ($user); $i + +) {
		echo \ $user [{$i}]=]. $user [$i]. " <br> ";
	}
	
	/**
	 	$user [0]=1
		$user [1]=zhasna
		$user [2]=aaa@bb.com
	 * *
?>

4.2 Loop traversal using a foreach statement (highly recommended)

The number of loops is determined by the number of elements in the array, and each loop assigns the elements in the array to the following variables

<?php
    $user =array (1, "name" => "Zhasna", "Age" =>40, 100=> "Nan", "aaa@bb.com");
    foreach ($user as $key => $val) {   //$var is a custom variable, $key the custom variable
  		echo $key. "=====>". $val. " <br> ";
    }
    
    /*
     	0 =====> 1
		name =====> Zhasna age
		=====>
		=====> nan-
		=====> aaa@bb.com
     /
    
    foreach ($user as $val) {   //Not key can also directly traverse $user value
  		echo $val. " <br> ";
    }
    
    /
     	*
     	1
		zhasna
		nan
		aaa@bb.com
     * *
?>

4.3 using while (), list (), each () combined loop traversal (not recommended)

each () function:

* requires an array as an argument

* The return is also an array

* Returns the array when 0, 1, key, value four subscript, 0 and key subscript is the key of the current array element, 1 and value subscript is the value of the current array element

* The default current element is the first element

* Move the current element backward after each execution

* If you have already done this function at the end, return false

<?php
	$user = array ("id" =>1, "name" => "Zhangsan", "Age" =>10, "Sex" => "Nan");
	
	while ($arr = each ($user)) {
		//echo $arr [0]. " ==> ". $arr [1]." <br> ";
		echo $arr ["Key"]. "---->". $arr ["Value"]. " <br> ";
	}
	
	/**
	 	ID----> 1
		name----> Zhangsan age
		---->
		sex----> Nan
	 * *
?>

List () function:

* List () =array (); You need to assign an array to this function

* The number of elements in the array is the same as the number of parameters in the list () function
* Each element value in the array is assigned to each parameter in the list () function, and list () converts each argument to a variable

* List () can only receive indexed arrays

<?php
	list ($name, $age, $sex) = Array ("Zansan", "nnnnn");
	echo $name. " <br> ";
	echo $age. " <br> ";  The values in the list and the value one by one in the array correspond to the
	echo $sex. " <br> ";  If you do not want to assign a value to name, then write list (, $age, $sex)/
	*
	 	Zansan
		nnnnn/
	 
	$user 1 = array ("id" =>1, " Name "=>", "Zhangsan", "Age" =>10, "Sex" => "Nan");
	List ($key, $value) = each ($user 1);  Array ([1] => 1  [0] => ID  ) 
	echo $key. "-->". $value;
	 	/* ID--> 1
	 *
	
	/$user 2 = array ("id" =>1, "name" => "Zhangsan", "Age" =>10, "Sex" => "Nan");
	while (the list ($key, $value) = each ($user 2)) {
		echo $key. "==>". $value. " <br> ";
	}
	/*
	 	name ==> Zhangsan age
		==>
		sex ==> nan
	 */
?>

Five, predefined arrays

Automatic global variables--Super global arrays
1. Contains data from the Web server, client, running environment and user input
2. Predefined arrays automatically take effect globally, for example, in functions where global is not declared and can use these arrays
3. Users cannot customize these arrays, but these data are manipulated in the same way as our custom array operations

* $_get//variable submitted to script via URL request
* $_post//variable submitted to script via HTTP POST method
* $_request//The variables submitted to the script via get, post and cookie mechanisms, so the array is not trustworthy and tries not to use
* $_files//variable submitted to script via HTTP POST file upload
* $_cookie//
* $_session//
* $_env//Execution Environment submitted to script variables
* $_server//variables are set by the Web server or are directly associated with the execution environment of the current script
* $GLOBALS//As long as the current script valid variables are here, the array key name is the name of the global variable

<?php
	Print_r ($_get);
	echo $_get["username"]. " <br> "; Gets the username
	
	print_r ($_post) in the Get way URL;
	echo $_post["uname"]. " <br> "; Gets the uname
	
	print_r ($_request) for the Post method form submission;
	echo $_env["OS"]. " <br> ";  Gets the value
	echo $_server["Document_root" for key ' OS '. <br> ";  Gets the value $a = 100 of the key ' Document_root '
	
	;//The defined variable is saved to the $globals
	function demo () {
		echo $GLOBALS ["a"]. " <br> ";  No need to declare global can directly take value
	}
	
	demo ();
? >

<form action= "demo.php" method= "POST" >   <!--Post to submit data, the data will be stored in $_post-->
	: <input type= "text" name= "uname" ><br>
	Password: <input type= "password" name= "pass" ><br>
	<input type= "Submit" value= "Login" > <br>
</form>

<a href= "Demo.php?username=" Zhangsan ">this is a $_get test</a> <!--Get method submits data, data is stored in $_get

Vi. array-related functions

1. Array key/value operation related functions
* 1.1 array_values () returns all the values in the input array and creates a numeric index for them

<?php
	$array = Array (
		"size" => "XL",
		"color" => "gold"
	);
	Print_r (Array_values ($array));
	/* Array
	(
	    [0] => XL
	    [1] => gold
	)
 * *
* 1.2 Array_keys () returns all the key names in the array

<?php
	$array = Array (
		0 =>,
		"color" => "red"
	);
	Print_r (Array_keys ($array));
 	/* Array (
	    [0] => 0
	    [1] => color
	) */
?>
* 1.3 In_array () check whether a value exists in the array

<?php
	$os = Array ("Mac", "NT", "Irix", "Linux");
	if (In_array ("Irix", $os)) {
		echo "Got Irix";
	}
	if (In_array ("Mac", $os)) {
		echo "Got mac";
	}
? >
* 1.4 Array_key_exists returns when a given key exists in an array TRUE

<?php
	$search _array = Array (
		' => ' 1,
		' second ' => 4
	);
	if (array_key_exists (' i ', $search _array)) {
		echo "the ' '" ' "The ' '" ' "", ""
>
* 1.5 The keys and values in the Array_flip Exchange array

<?php
	$trans = Array (
		"a" => 1,
		"B" => 1,
		"C" => 2
	);
	$trans = Array_flip ($trans);
	Print_r ($trans);  Array ([1] => b [2] => C) 
	//If the same value occurs more than once, the last key name is the value, and all the others are lost
* 1. 6 Array_reverse Returns an array of cells in reverse order
<?php
	$input = Array (
		"PHP",
		4.0,
		Array (
			"green",
			"Red"
		)
	);
	$result = Array_reverse ($input);
	Print_r ($result);
	Array ([0] => Array ([0] => Green [1] => red) [1] => 4 [2] => PHP) 
2. Statistics of the number and uniqueness of array elements
* 2. 1 count () sizeof ();

<?php
	$a [0] = 1;
	$a [1] = 3;
	$a [2] = 5;
	$result = count ($a);
	Print_r ($result);  3
* 2. 2 array_count_values count occurrences of all values in the array

<?php
	$array = Array (
		1,
		"Hello",
		1,
		"World",
		"Hello"
	);
	echo "<pre>";
	Print_r (Array_count_values ($array));
	echo "</pre>";
 	/* Array
	(
	    [1] => 2
	    [Hello] => 2
	    [World] => 1
	)
 * *
* 2. 3 Array_unique The duplicate values in the divisor group

<?php
	$input = Array ("A" => "green", "Red", "B" => "green", "Blue", "Red");
	$result = Array_unique ($input);
	echo "<pre>";
	Print_r ($result);
	echo "</pre>";
 	/* Array
	(
	    [a] => green
	    [0] => Red
	    [1] => blue
	)
 * *
3. Functions that use callback functions to handle arrays

* 3.1 Array_filter () filter the cells in the array with the callback function

<?php
	function Odd ($var) {
		//returns whether the input integer is odd return
		($var & 1);
	}
	
	$array = Array (
		"a" => 1,
		"B" => 2,
		"C" => 3
	);
	
	echo "<pre>";
	Print_r (Array_filter ($array, "odd"));
	echo "</pre>";
 	/* Array
	(
	    [a] => 1
	    [C] => 3
	)
 */

* 3.2 Array_walk () Use user-defined function to do callback with each element in the array

<?php
	$fruits = Array (
		"D" => "Lemon",
		"a" => "orange",
		"B" => "banana",
		"C" => "APPL" E "
	);
	
	FuncName accepts two parameters. The value of the array parameter is the first, and the key name is the second.
	function Test_print ($item, $key) {
		echo "$key =>  $item <br/>\n";
	}
	
	Array_walk ($fruits, ' test_print '); 
	
	*
		d => Lemon
		a => orange
		b => Banana
		c => Apple 
	 * *

* 3.3 Array_map () functions The callback function to the cell of the given array

<?php
	function Cube ($n) {return
	    ($n * $n * $n);
	}
	
	$a = Array (1, 2, 3, 4, 5);
	$b = Array_map ("cube", $a);
	Print_r ($b);
	Array ([0] => 1 [1] => 8 [2] => [3] => [4] => 125) 

4. Sorting function of array
* 4.1 sort () Rsort () simple array ordering

<?php
	$fruits  = Array ("Lemon", "orange", "banana", "apple");
	Sort ($fruits);
	foreach ($fruits as $key => $val) {
	    echo  "fruits[". $key. "] = " . $val. "<br>";
	}
	
/*
 	fruits[0] = Apple
	fruits[1] = Banana
	fruits[2] = Lemon
	fruits[3] = orange/
?>
* 4.2 ksort () Krsort () sort by array of key names

<?php
	$fruits = Array ("D" => "Lemon", "a" => "Orange", "B" => "banana", "C" => "Apple");
	Ksort ($fruits);
	foreach ($fruits as $key => $val) {
	    echo "$key = $val <br>";
	}
	
*
	 a = orange
	 b = Banana
	 c = Apple
	 d = Lemon 
 * *
?>  
* 4.3 asort () arsort () sort based on the value of the element

<?php
	$fruits = Array ("D" => "Lemon", "a" => "Orange", "B" => "banana", "C" => "Apple");
	Asort ($fruits);
	foreach ($fruits as $key => $val) {
	    echo "$key = $val <br>";
	}
	
/*
	C = Apple
	b = Banana
	d = lemon
	a = orange 
 * *
* 4.4 Natsort () natcasesort () sort the array according to the "Natural number Sort" method

<?php
	$array = Array ("Img12.png", "Img10.png", "Img2.png", "img1.png");
	Asort ($array);
	echo "<pre>";
	Print_r ($array);
	echo "</pre>";
	/* Array
	(
	    [3] => img1.png
	    [1] => img10.png
	    [0] => img12.png
	    [2] => img2.png
	)
 * *
?>
* 4.5 Usort () Uasort () Uksort () sorting based on user custom rules

<?php
	Function cmp ($a, $b) {
	    if ($a = = $b) {return
	        0;
	    }
	    Return ($a < $b)? -1:1;
	}
	$a = Array (3, 2, 5, 6, 1);
	Usort ($a, "CMP");
	foreach ($a as $key => $value) {
	    echo $key: $value <br>;
	}
	
/*
	0:1
	1:2
	2:3
	3:5
	4:6 
 * *
 
* 4.6 Array_multisort to sort multiple arrays at once

5. Array functions for splitting, merging, decomposing, and joining
* 5.1 array_slice () take a paragraph out of the array
* 5.2 Array_splice () remove part of the array and replace it with other values
* 5.3 Array_combine () creates an array with the value of one array as its key name and the value of the other array as its value
* 5.4 Array_merge () merge one or more arrays
* 5.5 array_intersect () compute the intersection of arrays
* 5.6 Array_diff () Compute the difference set of an array

6. The function of array and data structure
* 6.1 Array_push () Array_pop () using the data implementation stack
* 6.2 Array_unshift () Array_shift () unset () using queues

7. Other functions related to data manipulation
* 7.1 array_rand () randomly remove one or more cells from the array
* 7.2 Shuffle () to disrupt the array
* 7.3 array_sum () computes the and of all the values in the array
* 7.4 range () creates an array containing the specified range of cells



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.