How to use arrays in PHP

Time:2020-7-29

1. How does PHP get the number of elements in an array

In PHP, count() function is used to count the number of elements in the array.

For example, use the count() function to count the number of array elements. The example code is as follows:


<?php
header("Content-Type:text/html; charset=utf-8");
$arr = array("php","thinkphp","laravel");
echo count($arr);

The output results are as follows:

3

In the following example, the course data is stored in an array, and the count() function is used to recursively count the number in the array and output. The specific code is as follows:


<?php
header("Content-Type:text/html; charset=utf-8");
$arr = array(
 "php"=>array("php","thinkphp","laravel"),
 "js"=>array("vue","react")
);
echo count($arr,true);

The output results are as follows:

7

Note: when counting two-dimensional arrays, if you directly use the count() function, only the number of one-dimensional arrays will be displayed, so use recursive to count the number of two-dimensional arrays!

2. How does PHP query the specified elements in an array

array_ The search() function searches for the given value in the array and returns the key value after it is found. Otherwise, it returns false. Before PHP 4.2.0, functions returned null instead of false on failure.

The following example comprehensively applies array functions to update the values of elements in the array. The specific example code is as follows:

<?php
header("Content-Type:text/html; charset=utf-8");

$names = "watch 1 @ watch 2 @ watch 3 @ watch 4"; ";
$prices = "[email protected]@[email protected]";
$counts = "[email protected]@[email protected]";
$arrname = expand ("@", $names); // ['watch 1 ','watch 2','watch 3 ','watch 4']
$arrprice = explode("@",$prices); //['111','222','333','444']
$arrcount = explode("@",$counts); //['1','3','5','2']

if($_POST){
 $name = $_POST['name'];
 $count = $_POST['count'];
 $key= array_ Search ($name, $arrname); // get the key name of the data to be changed
 $arrcount[$key] = $count; 
}

?>

<table width="500" birder="1" cellpadding="1" bordercolor="#fff" bgcolor="#c17e50">
 <tr>
  < TD width = "145" align = "center" bgcolor ">" FFF "> trade name</td>
  < TD width = "145" align = "center" bgcolor ">" FFF "> unit price</td>
  < TD width = "145" align = "center" bgcolor = "FFF" > quantity</td>
  < TD width = "145" align = "center" bgcolor = "FFF" > total price</td>
 </tr>
 <?php
 $sum = 0;
 for($i=0;$i<count($arrname);$i++){  
 ?>
 <form action="#" method="post" name="form-<?php echo $i; ?>">
  <tr>
   <td width="145" align="center" bgcolor="#fff"><?php echo $arrname[$i]; ?></td>
   <td width="145" align="center" bgcolor="#fff"><?php echo $arrprice[$i]; ?></td>
   <td width="145" align="center" bgcolor="#fff">
    <input type="text" name="count" value="<?php echo $arrcount[$i]; ?>" size="4">
    <input type="hidden" name="name" value="<?php echo $arrname[$i]; ?>">
    < input type = submit "type = submit" value = change ">
   </td>
   <td width="145" align="center" bgcolor="#fff"><?php echo $arrprice[$i]*$arrcount[$i]; ?></td>
  </tr>
 </form>
 <?php
 $sum += $arrprice[$i]*$arrcount[$i];;
 }
 ?>
 <tr>
  <td>Total orders:</td>
  <td colspan="3"><?php echo $sum; ?></td>
 </tr>

</table>

Description: array_ The most common application of search() function is shopping cart, which can modify and delete the specified quantity of goods in the shopping cart!

3. Example of conversion between PHP one dimensional array and two dimensional array

One dimensional array conversion two-dimensional array example code:


<?php
header("Content-Type:text/html;charset=utf-8");

$arr[1] = array("a1","a2");
$arr[2] = array("b1","b2");

$newarr = array();
foreach($arr as $a){
 $newarr[] = $a;
}
print_r($newarr);

The output results are as follows:

How to convert a two-dimensional array into a one-dimensional array:


<?php
header("Content-Type:text/html;charset=utf-8");

$arr = array(
 array(
  'id'=>1,
  'name'=>'cyy1'
 ),
 array(
  'id'=>2,
  'name'=>'cyy2'
 )
);

$ids = array_column($arr,'id');
$names = array_column($arr,'name');
print_r($names);

The results were as follows

Note: array_ Column(); can have a third parameter, such as $n = array_ column($arr, ‘name’, ‘id’);


<?php
header("Content-Type:text/html;charset=utf-8");

$arr = array(
 array(
  'id'=>1,
  'name'=>'cyy1'
 ),
 array(
  'id'=>2,
  'name'=>'cyy2'
 )
);

$names = array_column($arr,'name','id');
print_r($names);

The results were as follows

4. How to loop the output of array in PHP? The method of traversing array

The first is to traverse the array using the foreach structure


<?php
header("Content-Type:text/html;charset=utf-8");

$arr = array(
 'course1'=>'php',
 'course2'=>'thinkphp',
 'course3'=>'laravel',
);

foreach($arr as $k=>$v){
 echo $v.'<br/>';
}

The results are as follows:

php

thinkphp

laravel

The second: the list() function traverses the array

The list() function can only be used for arrays with a numeric index starting at 0

The following will explain the comprehensive application of the list() function and each() function through specific examples to obtain the user login information stored in the group number.

The specific development steps are as follows:

1. Create a PHP dynamic page with development tools and save it as index.php 。

2. Using HTML tag to design the page. Firstly, the user login form is created to input the user login information, and then the global array is extracted by each() function$_ The content of post, and finally uses the white statement to output the attention information submitted by the user.

The example code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>index</title>
</head>
<body>
 <form name="form1" method="post">
  <table width="323" border="1" cellpadding="1" cellspacing="1" bordercolor="#66cc33" bgcolor="#fff">
   <tr>
    < TD width = "118" height = "24" bgcolor ">" ccff33 "> user name</td>
    <td width="192" height="24" bgcolor="#ccff33">
     <input type="text" name="username" size="24">
    </td>
   </tr>
   <tr>
    < TD height = "24" bgcolor = "ccff33" > password</td>
    <td height="24" bgcolor="#ccff33">
     <input type="password" name="pwd" size="24">
    </td>
   </tr>
   <tr>
    <td height="24" colspan="2">
     < input type = "submit" name = "submit" value = login ">
    </td>
   </tr>
  </table>
 </form>
</body>
</html>

<?php

while(list($name,$value)=each($_POST)){
 if($name!="submit"){
  echo "$name=$value<br/>";
 }
}

The operation results are as follows:

explain:

The each() function returns the array value of the current pointer position and advances the pointer to the next position. The returned array contains four keys, keys 0 and key contain key names, while keys 1 and value contain corresponding data. False if the pointer is already at the end of the array when the program executes the each() function.

5. PHP array and string conversion

1. Use the expand() function to convert a string into an array


<?php
header("Content-Type:text/html;charset=utf-8");

$str = "i am learning php";
$arr = explode(" ", $str);
print_r($arr);

The output results are as follows:

In the development of a voting management system, it is often necessary to add voting options to the voting system in the background as the content of voting. Next, use the expand() function to distinguish the added voting options by “*”, and then use the white loop statement to output the added voting options in the surface.

The specific development steps are as follows:

(1) Use development tools to create a PHP dynamic page and save it as index.php 。

(2) Using HTML tag design surface, first create a voting form to add voting options, and then use each() function to extract the global array$_ The content in post, and finally uses the while loop to output the voting option content. The code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>index</title>
</head>
<body>
 <form action="#" name="form1" method="post">
  <table width="400" border="1" cellpadding="0" cellspacing="1" bordercolor="#ff9900" bgcolor="#ccff66">
   <tr>
    < TD width = "98" height = "120" > Add voting options</td>
    <td width="223" height="120">
     <p>
      <textarea name="content" cols="30" rows="5"></textarea><br>
      <span>Note: each option is separated with a *</span>
     </p>
    </td>
    <td width="61" height="120">
     < input type = submit "name =" submit "value = submit" >
    </td>
   </tr>
  </table>
 </form>
</body>
</html>

<?php
if($_POST['submit'] != ''){
 $content = $_POST['content'];
 $data = explode("*",$content);
 while(list($name,$value) = each($data)){
  echo '<input type="checkbox" name="checkbox" value="checkbox">';
  echo $value."\n";
 }
}

The results are as follows

2. Use implode() function to convert the array into a string


<?php
$arr = array(1,2,3,4);
$str = implode($arr);
echo $str;

The output results are as follows:

1234

6. PHP output array – print array example details

Print is generally used_ R to print the array (VaR, of course)_ Dump is OK, but the structure is not clear)


<?php
$arr = array(1,2,3,4);
print_r($arr);

When the second parameter is true, print_ R does not print the array directly, but returns the printed content as a string


<?php
$arr = array(1,2,3,4);
echo print_r($arr,true);

The above is how to use arrays in PHP. For more information about arrays in PHP, please pay attention to other related articles in developeppaer!