Table of Contents
Key/value operation function of array, array function
Read n from the keyboard Put the integers into the array, write the function CompactIntegers, delete all elements with a value of 0 in the array, and then add the elements to the array
After the PHP array is shuffled using the shuffle function, duplicate values ​​appear in different keys
Home Backend Development PHP Tutorial Array key/value operation functions, array functions_PHP tutorial

Array key/value operation functions, array functions_PHP tutorial

Jul 13, 2016 am 10:21 AM
value element function exist operate array of composition access pass key

Key/value operation function of array, array function

PHIn P, each element of the array is composed of key/value Composed, the value of the corresponding key is accessed through the key of the element. "Associative array" refers to an array with a string key name, and "index" and "key name" refer to the same thing. "index" The numeric subscript of a multi-exponent array. Using the array processing function, you can easily operate on the key and value of each element in the array to generate a new array.

①Function array_values()

The array_values() function is to return the values ​​of all elements in the array. It is very easy to use. There is only one required parameter, which specifies that the given array is passed in and an array containing all the values ​​in the given array is returned. But the key names are not preserved, and the returned array will be re-indexed using sequential numeric keys, starting at 0 and increasing by 1. It is suitable for arrays with chaotic elements in the array, or can convert associative arrays into indexed arrays. The code looks like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?php $contact = array( "ID" => 1, "姓名" => "高某", "公司" => "A公司", "地址" => "北京市", "电话" => "(010)98765432" );   //array_values()函数传入数组$contact 重新索引返回一个新数组   print_r(array_values($contact)); print_r($contact); //原数组$contact内容元素不变 ?>

The result after running the program is as follows:
Array([0]=>1 [1]=>Gao [2]=>Company A[3]=> Beijing[4]=>(010)98765432)
Array([ID]=>1 [Name]=>Gao [Company]=>Company A [Address] => Beijing [Tel] =>(010)98765432)

②Function array_keys()

The array_keys() function is to return all the key names in the array. This function has one required parameter and two optional parameters. The prototype of its function is as follows:

array array_keys(array input[,mixed search_value[,bool strict]])
If the optional parameter search_value is specified, only the key name of the specified value will be returned, otherwise the key name in the input array All key names will be returned. Since PHP5, you can use the strict parameter to perform congruent comparisons. A Boolean value needs to be passed in. FALSE is the default value and does not depend on the type. If a TRUE value is passed in, the key name with the specified value is returned according to the type. The code used by the function array_keys() is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 <?php $lamp = array("a"=>"Linux","b"=>"Apache","c"=>"MySQL","d"=>"php"); print_r(array_keys($lamp)); //输出Array([0]=>a [1]=>b [2]=>c) print_r(array_keys($lamp,"Apache")); //使用第二个可选参数输出:Array([0]=>b)   $a = array(10,20,30,"10"); //声明一个数组,其中元素的值有整数10和字符串"10" print_r(array_keys($a,"10",false)); //使用第三个参数(false)输出:Array([0]=>0 [1]=>3)   $a = array(10,20,30,"10"); //声明一个数组,其中元素的值有整数10和字符串"10" print_r(array_keys($a,"10",true)); //使用第三个参数(true)输出:Array([0]=>3)   ?>

③Function in_array()

The function of

in_array() function is to check whether a certain value exists in the array, that is, to search for a given value in the array. There are three parameters in this function, the first two parameters are required, and the last parameter is optional. The prototype of its function is as follows:

bool in_array(mixed needle,array haystack[,bool strict])

The first parameter needle specifies the value to be searched in the array, and the second parameter haystack specifies the array to be searched. If the given value needle exists in the array haystack, TRUE is returned. If the third parameter is set to TRUE, the function returns TRUE only if the element exists in the array and has the same data type as the given value. If the parameter is not found in the array, the function returns FALSE. Note that if the needle parameter is a string and the strict parameter is set to TRUE, the search is case-sensitive. The code used by the function array_keys() is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 <?php //in_array()函数的简单使用形式 $os = array("Mac","NT","Trix","Linux");   if(in_array("Trix",$os)){ //这个条件成立,字符串Trix在数组$os中 echo "Got Trix"; }   if(in_array("mac",$os)){ //这个条件失败,因为in_array()是区分大小写的 echo "Got mac"; }   //in_array严格类型检查例子 $a = array('1.10',12.4,1.13);   //第三个参数为true,所以字符串'12.4'和浮点数12.4类型不同 if (in_array('12.4',$a,true)){ echo "'12.4' found with strict checkn"; }   if (in_array(1.13,$a,true)){ //这个条件成立,执行下面的语句 echo "1.13 found with strict checkn"; }       <code class="php spaces"> //in_array()中还可以用数组当做第一个参数作为查询条件<code class="php comments">//in_array()中还可以用数组当做第一个参数作为查询条件     <code class="php spaces"> $a<code class="php variable">$a = <code class="php plain">= array<code class="php keyword">array(<code class="php plain">(array<code class="php keyword">array(<code class="php plain">('p'<code class="php string">'p',<code class="php plain">,'h'<code class="php string">'h'),<code class="php plain">),array<code class="php keyword">array(<code class="php plain">('p'<code class="php string">'p',<code class="php plain">,'r'<code class="php string">'r'),<code class="php plain">),'o'<code class="php string">'o');<code class="php plain">);       <code class="php spaces"> if<code class="php keyword">if(in_array(<code class="php plain">(in_array(array<code class="php keyword">array(<code class="php plain">('p'<code class="php string">'p',<code class="php plain">,'h'<code class="php string">'h'),<code class="php plain">),$a<code class="php variable">$a)){            <code class="php plain">)){ //数组array('p','h')在数组$a中存在<code class="php comments">//数组array('p','h')在数组$a中存在         <code class="php spaces"> echo<code class="php functions">echo "'ph'was foundn"<code class="php string">"'ph'was foundn";<code class="php plain">;     <code class="php spaces"> }<code class="php plain">}       <code class="php spaces"> if<code class="php keyword">if(in_array(<code class="php plain">(in_array(array<code class="php keyword">array(<code class="php plain">('h'<code class="php string">'h',<code class="php plain">,'p'<code class="php string">'p'),<code class="php plain">),$a<code class="php variable">$a)){            <code class="php plain">)){ //数组array('h','p')在数组$a中不存在<code class="php comments">//数组array('h','p')在数组$a中不存在         <code class="php spaces"> echo<code class="php functions">echo "'hp'was foundn"<code class="php string">"'hp'was foundn";<code class="php plain">;     <code class="php spaces"> }<code class="php plain">} ?>?>

You can also use the array_search() function to search. This function has the same parameters as in_array(). It searches for a given value and returns the corresponding key name if it exists. It also supports strict judgment on the data type. The code used by the function array_search() is as follows:

1 2 3 4 5 6 7 <?php $lamp = array("a"=>"Linux","b"=>"Apache","c"=>"MySQL","d"=>"php");     echo array_search("php",$lamp);         //输出:d(在数组$lamp中,存在字符串"php"则输出下标d)       $a = array("a"=>"8","b"=>8,"c"=>"8");     echo array_search(8,$a,ture);           //输出b(严格按类型检索,整型8对应的下标b) ?>

In addition, using the array_key_exists() function you can also check whether a given key name or index exists in the array. Because the key name must be unique in an array, there is no need to judge its data type. You can also use the isset() function to check the key names in the array. Single isset() will not return TRUE for NULL values ​​in the array, but array_key_exists() will. The code looks like this:

1 2 3 4 5 6 7 8 9 10 11 12 <?php $search_array = array('first'=>1,'second'=>4);            //声明一个关联数组,其中包含两个元素       if(array_key_exists('first',$search_arry)){             //检查下标为first对应的元素是否在数组中         echo "键名为'first'的元素在数组中";     }       $search_array = array('first'=> null,'second'=>4);            //声明一个关联数组,第二个元素的值为NULL       isset($search_array['first']);                  //用isset()检索下标为first的元素返回false     array_key_exists('first',$search_array);                //用array_key_exists()检索下标为first的元素返回true ?>

④Function array_flip()

The function of array_flip() is to exchange the keys and values ​​in the array. Returns a reversed array. If the same value appears multiple times, the last key name will be used as its value, overwriting the previous elements. If the value data type in the original array is not string or integer, the function will report an error. This function has only one parameter, and its function prototype is as follows:

array array_flip(trans)

The parameter is required and requires input of an array to be processed, and returns an array with the keys and values ​​of each element in the array exchanged. The code used by the function array_flip() is as follows:

1 2 3 4 5 6 7 8 9 10 <?php $lamp = array("os"=>"linux","WebServer"=>"Apache","Database"=>"MySQL","Language"=>"PHP");       //输出:Array([linux]=>os [Apache]=>WebServer [MySQL]=>Database [PHP]=Language);     print_r(array_flip($lamp));             //使用array_flip()函数交换数组中的键和值       //在数组中如果元素的值相同,则使用array_flip()会发生冲突     $trans = array("a"=>1,"b"=>1,"c"=2);     print_r(array_flip($trans));            //现在$trans变成了:Array([1]=> b [2]=> c) ?>

⑤Function array_reverse()

The function of array_reverse() is to reverse the order of elements in the original array, create a new array and return it. This function has two parameters, and its function prototype is as follows:

array array_reverse(array array[,bool preserve_keys])

The first parameter is required and receives an array as input. The second parameter is optional. If TRUE is specified, the key name of the element remains unchanged, otherwise the key name will be lost. The code used by the function array_reverse() is as follows:

1 2 3 4 5 6 7 <?php $lamp = array("OS"=>"Linux","WebServer"=>"Apache","Database"=>"MySQL","Language"=>"PHP");       //使用array_reverse()函数将数组$lamp中的元素的顺序翻转     print_r(array_reverse($lamp));     //输出的结果Array([Language]=>PHP [Database]=>MySQL [WebServer]=>Apache  [OS]=>Linux) ?>

>> Fixed link to this article: http://php.ncong.com/php_course/arry_function/key-value.html

Read n from the keyboard Put the integers into the array, write the function CompactIntegers, delete all elements with a value of 0 in the array, and then add the elements to the array

#include
int Compactlntegers(int a[], int *m)
{
int i,j,n;//I used the C compiler to do it here, So I modified it a bit,
//If it’s C++, you should be able to use reference to pass value directly. According to what you originally wrote, you should be able to modify the value of n in the main program
n=*m;
for(i= 0;i {
if(a[i]==0)
{
for(j=i;ja[j ]=a[j+1];
n--;
}
}
*m=n;
return j;
}
void main()
{
int i,n,a[100];
printf("please input your number:\n");
scanf("%d",&n);
for( i=0;i {
printf("please input the %d number:",i+1);
scanf("%d",&(a[i] ));
}
Compactlntegers(a,&n);
for(i=0;i {
printf("the %d number is: %d \n",i+1, a[i]);
}
}

After the PHP array is shuffled using the shuffle function, duplicate values ​​appear in different keys

What about the code?
Does your array originally have duplicate values?

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/860919.htmlTechArticleArray key/value operation function, array function PH In P, each element of the array is represented by a key / consists of values, and the value of the corresponding key is accessed through the key of the element. Associative array refers to the key name...
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)

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

See all articles