Loading... ## 如何在 PHP 中编写注释 ### Answer: Use the Syntax “// text” and “/\* text \*/” Comments are usually written within the block of PHP code to explain the functionality of the code. It will help you and others in the future to understand what you were trying to do with the PHP code. Comments are not displayed in the output, they are ignored by the PHP engine. ### Single Line Comments PHP single line comment begins with //, See the example below: ```php <?php echo "Hello World!"; // Output "Hello World!" ?> ``` ### Multi-line Comments PHP multi-line line comment begins with /\*, and ends with \*/. ```php <?php /* The following line of code will output the "Hello World!" message */ echo "Hello World!"; ?> ``` ## 如何在 PHP 中删除字符串中的空格 ### Answer: Use the PHP trim() function You can use the PHP trim() function to remove whitespace including non-breaking spaces, newlines, and tabs from the beginning and end of the string. It will not remove whitespace occurs in the middle of the string. Let’s take a look at an example to understand how it basically works: ```php <?php $my_str = ' Welcome to Tutorial Republic '; echo strlen($my_str); // Outputs: 33 $trimmed_str = trim($my_str); echo strlen($trimmed_str); // Outputs: 28 ?> ``` ## 如何在 PHP 中查找字符串中的字符数 ### Answer: Use the PHP strlen() function You can simply use the PHP strlen() function to find the number of characters in a string of text. It also includes the white spaces inside the specified string. Let’s take a look at the following example to understand how it basically works: ```php <?php $my_str1 = 'The quick brown fox jumps over the lazy dog.'; echo strlen($my_str1); // Outputs: 44 $my_str2 = ' The quick brown fox jumps over the lazy dog. '; echo strlen($my_str2); // Outputs: 49 ?> ``` ## 如何在 PHP 中查找字符串中的单词数 ### Answer: Use the PHP str\_word\_count() function PHP str\_word\_count() 函数可用于查找字符串中的单词数。 让我们通过一个示例来了解该函数的基本工作原理: ```php <?php $my_str = 'The quick brown fox jumps over the lazy dog.'; // Outputs: 9 echo str_word_count($my_str); ?> ``` ## 如何在 PHP 中删除字符串中的特殊字符 ### Answer: Use the PHP htmlspecialchars() function Certain characters such as (&, ", ', <, >) have special significance in HTML, and should be converted to HTML entities. You can use the PHP htmlspecialchars() function to convert special characters in a string to HTML entities. Let’s check out an example: ```php <?php $my_str = "String with <b>special</b> characters."; // Removing HTML special characters echo htmlspecialchars($my_str); ?> ``` If you view the source code of the output you will the string “String with special characters.” converted to “String with <b>special</b> characters.” ## 如何在 PHP 中替换字符串中的一个单词 ### Answer: Use the PHP str\_replace() function You can use the PHP str\_replace() function to replace all the occurrences of a word within a string. In the following example the word “facts” is replaced by the word “truth”. ```php <?php $my_str = 'If the facts do not fit the theory, change the facts.'; // Display replaced string echo str_replace("facts", "truth", $my_str); ?> ``` The PHP str\_replace() function is case-sensitive, however if you want to perform case-insensitive match and replace you can use the str\_ireplace() function. ## 如何在 PHP 中对字符串前面追加 ### Answer: Use the PHP Concatenation Operator There is no specific function to prepend a string in PHP. But you can use the PHP concatenation operator (.) to prepened a string with another string. Let’s take a look at the following example to understand how it basically works: ```php <?php $a = "Hello"; $b = "World!"; $b = $a . " " . $b; echo $b; // Outputs: Hello World! ?> ``` See the tutorial on [PHP operators](http://www.bixiaguangnian.com/manual/php7/3971.html "PHP operators") to learn about the operators in detail. ## 如何在 PHP 中从字符串中提取子串 ### Answer: Use the PHP substr() function The PHP substr() function can be used to get the substring i.e. the part of a string from a string. This function takes the start and length parameters to return the portion of string. Let’s check out an example to understand how this function basically works: ```php <?php $str = "Hello World!"; echo substr($str, 0, 5); // Outputs: Hello echo substr($str, 0, -7); // Outputs: Hello echo substr($str, 0); // Outputs: Hello World! echo substr($str, -6, 5); // Outputs: World echo substr($str, -6); // Outputs: World! echo substr($str, -12); // Outputs: Hello World! ?> ``` ## 如何在 PHP 中比较两个字符串 ### Answer: Use the PHP strcmp() function You can use the PHP strcmp() function to easily compare two strings. This function takes two strings str1 and str2 as parameters. The strcmp() function returns < 0 if str1 is less than str2; returns > 0 if str1 is greater than str2, and 0 if they are equal. Let’s check out an example to understand how this function basically works: ```php <?php $str1 = "Hello"; $str2 = "Hello World"; echo strcmp($str1, $str2); // Outputs: -6 ?> ``` The PHP strcmp() function compare two strings in a case-sensitive manner. If you want case-insensitive comparison, you can use the strcasecmp() function. ## 如何在 PHP 中获取当前页面的 URL ### Answer: Use the PHP \$\_SERVER Superglobal Variable You can use the \$\_SERVER built-in variable to get the current page URL in PHP. The \$\_SERVER is a superglobal variable, which means it is always available in all scopes. Also if you want full URL of the page you’ll need to check the scheme name (or protocol), whether it is http or https. Let’s take a look at an example to understand how it works: ```php <?php $uri = $_SERVER['REQUEST_URI']; echo $uri; // Outputs: URI $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $url; // Outputs: Full URL $query = $_SERVER['QUERY_STRING']; echo $query; // Outputs: Query String ?> ``` ## 如何在 PHP 中通过连接数组值创建字符串 ### Answer: Use the PHP implode() or join() function You can use the PHP implode() or join() function for creating a string by joining the values or elements of an array with a glue string like comma (,) or hyphen (-). Let’s take a look at the following example to understand how it basically works: ```php <?php $array = array("red", "green", "blue"); // Turning array into a string $str = implode(", ", $array); echo $str; // Outputs: red, green, blue ?> ``` ## 如何在 PHP 中将字符串拆分为数组 ### Answer: Use the PHP explode() function You can use the PHP explode() function to split or break a string into an array by a separator string like space, comma, hyphen etc. You can also set the optional limit parameter to specify the number of array elements to return. Let’s try out an example and see how it works: ```php <?php $my_str = 'The quick brown fox jumps over the lazy dog.'; print_r(explode(" ", $my_str)); echo "<br>"; print_r(explode(" ", $my_str, 4)); ?> ``` ## 如何在 PHP 中合并两个字符串 ### Answer: Use the PHP Concatenation Operator You can use the PHP concatenation operator (.) to combine or join two strings together in PHP. This operator is specifically designed for strings. Let’s see how it works: ```php <?php $str1 = 'Hello'; $str2 = 'World!'; $new_str = $str1 . ' ' . $str2; echo $new_str; // Outputs: Hello World! ?> ``` ## 如何在 PHP 中把字符串转换成小写字母 ### Answer: Use the PHP strtolower() function You can use the PHP strtolower() function to convert a string to lowercase. Let’s check out the following example to understand how this function actually works: ```php <?php $my_str = 'The Quick Brown Fox Jumps Over The Lazy Dog.'; echo strtolower($my_str); ?> ``` ## 如何在 PHP 中把字符串转换成大写字母 ### Answer: Use the PHP strtoupper() function You can use the PHP strtoupper() function to convert a string to uppercase. Let’s try out the following example to understand how this function basically works: ```php <?php $my_str = 'The quick brown fox jumps over the lazy dog.'; echo strtoupper($my_str); ?> ``` ## 如何在 PHP 中把字符串的第一个字母转换成大写字母 ### Answer: Use the PHP ucfirst() function You can use the PHP ucfirst() function to change the first character of a string to uppercase (i.e. capital). Alternatively, you can use the strtolower() function in combination with the ucfirst() function, if you want to make only first letter of the string to uppercase and rest of the string to lowercase. Let’s check out an example to understand how it works: ```php <?php $str1 = 'the color of the sky is blue.'; echo ucfirst($str1); echo "<br>"; $str2 = 'the Color of the Sky is Blue.'; echo ucfirst(strtolower($str2)); ?> ``` ## 如何在 PHP 中把特殊的 HTML 实体转换回字符 ### Answer: Use the PHP htmlspecialchars\_decode() function You can use the PHP htmlspecialchars\_decode() function to convert the special HTML entities such as &, <, > etc. back to the normal characters (i.e. &, <, >). The htmlspecialchars\_decode() function is opposite of the htmlspecialchars() function which converts special HTML characters into HTML entities. Let’s check out an example: ```php <?php $my_str = "I'll come & <b>"get you"</b>."; // Decode &, <, > and " echo htmlspecialchars_decode($my_str); // Decode &, <, >, " and ' echo htmlspecialchars_decode($my_str, ENT_QUOTES); // Decode &, < and > echo htmlspecialchars_decode($my_str, ENT_NOQUOTES); ?> ``` ## 如何在 PHP 中删除字符串开头的空格 ### Answer: Use the PHP ltrim() function You can use the PHP ltrim() function to strip whitespace from the beginning of a string. Let’s take a look at an example to understand how this function really works: ```php <?php $my_str = ' Hello World!'; echo strlen($my_str); // Outputs: 16 $trimmed_str = ltrim($my_str); echo strlen($trimmed_str); // Outputs: 12 ?> ``` ## 如何在 PHP 中删除字符串结尾的空格 ### Answer: Use the PHP rtrim() function You can use the PHP rtrim() function to strip whitespace from the end of a string. Let’s check out an example to understand how this function basically works: ```php <?php $my_str = 'Hello World! '; echo strlen($my_str); // Outputs: 16 $trimmed_str = rtrim($my_str); echo strlen($trimmed_str); // Outputs: 12 ?> ``` ## 如何在 PHP 中新建一行 ### Answer: Use the Newline Characters ‘\\n’ or ‘\\r\\n’ You can use the PHP newline characters \\n or \\r\\n to create a new line inside the source code. However, if you want the line breaks to be visible in the browser too, you can use the PHP nl2br() function which inserts HTML line breaks before all newlines in a string. Let's take a look at the following example to understand how it basically works: ```php <?php echo "If you view the page source \r\n you will find a newline in this string."; echo "<br>"; echo nl2br("You will find the \n newlines in this string \r\n on the browser window."); ?> ``` > Note: The character \\n writes a newline in UNIX while for Windows there is the two character sequence: \\r\\n. To be on safe side use the \\r\\n instead. ## 如何在 PHP 中查找字符串长度 ### Answer: Use the PHP strlen() function You can simply use the PHP strlen() function to get the length of a string. The strlen() function return the length of the string on success, and 0 if the string is empty. Let’s take a look at the following example to understand how it actually works: ```php <?php $str1 = 'Hello world!'; echo strlen($str1); // Outputs: 12 echo "<br>"; $str2 = ' Hello world! '; echo strlen($str2); // Outputs: 17 ?> ``` ## 如何在 PHP 中检查变量是否已设置 ### Answer: Use the PHP isset() function You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Let's check out an example to understand how this function basically works: ```php <?php $var1 = ''; if(isset($var1)){ echo 'This line is printed, because the $var1 is set.'; } echo "<br>"; $var2 = 'Hello World!'; if(isset($var2)){ echo 'This line is printed, because the $var2 is set.'; } echo "<br>"; // Unset the variable unset($var2); if(isset($var2)){ echo 'This line is printed, because the $var2 is set.'; } else { echo 'This line is printed, because the $var2 is not set.'; } echo "<br>"; $var3 = NULL; if(isset($var3)){ echo 'This line is printed, because the $var3 is set.'; } else { echo 'This line is printed, because the $var3 is not set.'; } ?> ``` ## 如何在 PHP 中检查变量是否为空 ### Answer: Use the PHP empty() function You can use the PHP empty() function to find out whether a [variable](http://www.bixiaguangnian.com/manual/php7/3966.html "variable") is empty or not. A variable is considered empty if it does not exist or if its value equals FALSE. Let’s try out the following example to understand how this function basically works: ```php <?php $var1 = ''; $var2 = 0; $var3 = NULL; $var4 = FALSE; $var5 = array(); // Testing the variables if(empty($var1)){ echo 'This line is printed, because the $var1 is empty.'; } echo "<br>"; if(empty($var2)){ echo 'This line is printed, because the $var2 is empty.'; } echo "<br>"; if(empty($var3)){ echo 'This line is printed, because the $var3 is empty.'; } echo "<br>"; if(empty($var4)){ echo 'This line is printed, because the $var4 is empty.'; } echo "<br>"; if(empty($var5)){ echo 'This line is printed, because the $var5 is empty.'; } ?> ``` > Note: The empty() function does not generate a warning if the variable does not exist. That means empty() is equivalent to !isset(**var) || **var == false. ## 如何在 PHP 中检查变量是否为NULL ### Answer: Use the PHP is\_null() function You can use the PHP is\_null() function to check whether a [variable](http://www.bixiaguangnian.com/manual/php7/3966.html "variable") is null or not. Let’s check out an example to understand how this function works: ```php <?php $var = NULL; // Testing the variable if(is_null($var)){ echo 'This line is printed, because the $var is null.'; } ?> ``` The is\_null() function also returns true for undefined variable. Here’s a example: ```php <?php // Testing an undefined variable if(is_null($inexistent)){ echo 'This line is printed, because the $inexistent is null.'; } ?> ``` ## 如何在 PHP 中反转字符串 ### Answer: Use the PHP strrev() function You can use the PHP strrev() to reverse the text writing direction of a [string](http://www.bixiaguangnian.com/manual/php7/3970.html "string"). Let’s take a look at an example to understand how it basically works: ```php <?php echo strrev("Hello world!"); // Outputs: "!dlrow olleH" ?> ``` ## 如何在 PHP 中用另一个字符串替换字符串的一部分 ### Answer: Use the PHP str\_replace() function You can use the PHP str\_replace() function to find and replace any portion of a string with another string. In the following example the substring “quick brown fox” of the string \$my\_str is replaced by the string “swift white cat”. Let’s try it out and see how it works: ```php <?php $my_str = "The quick brown fox jumps over the lazy dog."; // Display replaced string echo str_replace("quick brown fox", "swift white cat", $my_str); ?> ``` ## 如何在 PHP 中计算子串在字符串中出现的次数 ### Answer: Use the PHP substr\_count() function You can use the PHP substr\_count() function to find out how many times a given substring is appears or repeated inside a string. Let’s try out an example to see how it works: ```php <?php $quote = "Try not to become a man of success, but rather try to become a man of value."; echo substr_count($quote, 'man'); // Outputs: 2 ?> ``` ## 如何在 PHP 中计算数组中的所有元素 ### Answer: Use the PHP count() or sizeof() function You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn’t set. You can additionally use the isset() function to [check whether a variable is set or not](http://www.bixiaguangnian.com/manual/php7/4048.html "check whether a variable is set or not"). ```php <?php $days = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"); // Printing array size echo count($days); echo "<br>"; echo sizeof($days); ?> ``` ## 如何在 PHP 中打印或回显数组的所有值 ### Answer: Use the PHP foreach loop There are so many ways of printing an array values, however the simplest method is using the [foreach loop](http://www.bixiaguangnian.com/manual/php7/3976.html "foreach loop"). In the following example we’ve iterated over the \$colors array and print all its elements using the [echo or print statement](http://www.bixiaguangnian.com/manual/php7/3968.html "echo or print statement"). Let’s try it out and see how it works: ```php <?php $colors = array("Red", "Green", "Blue", "Yellow", "Orange"); // Loop through colors array foreach($colors as $value){ echo $value . "<br>"; } ?> ``` ## 如何在 PHP 中显示数组的结构和值 ### Answer: Use the PHP print\_r() or var\_dump() Statement You can either use the PHP print\_r() or var\_dump() statement to see or check the structure and values of an array in human-readable format on the screen. The var\_dump() statement however gives more information than print\_r(). Let’s see how it basically works: ```php <?php $cities = array("London", "Paris", "New York"); // Print the cities array Print_r($cities); echo "<hr>"; var_dump($cities); ?> ``` ## 如何在 PHP 中颠倒数组的顺序 ### Answer: Use the PHP array\_reverse() function You can use the PHP array\_reverse() function to reverse the order of the array elements. Let’s try out an example to understand how this function actually works: ```php <?php $colors = array("Red", "Green", "Blue"); // Printing the reversed array print_r(array_reverse($colors)); ?> ``` ## 如何在 PHP 中检查数组中是否存在值 ### Answer: Use the PHP in\_array() function You can use the PHP in\_array() function to test whether a value exists in an array or not. Let’s take a look at an example to understand how it basically works: ```php <?php $zoo = array("Lion", "Elephant", "Tiger", "Zebra", "Rhino", "Bear"); if(in_array("Elephant", $zoo)){ echo "The elephant was found in the zoo."; } echo "<br>"; if(in_array("Tiger", $zoo)){ echo "The tiger was found in the zoo."; } ?> ``` ## 如何在 PHP 中检查数组中是否存在键 ### Answer: Use the PHP array\_key\_exists() function You can use the PHP array\_key\_exists() function to test whether a given key or index exists in an array or not. This function returns TRUE on success or FALSE on failure. Let’s take a look at the following example to understand how it actually works: ```php <?php $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York"); // Testing the key exists in the array or not if(array_key_exists("France", $cities)){ echo "The key 'France' is exists in the cities array"; } ?> ``` ## 如何在 PHP 中删除数组中的最后一个元素 ### Answer: Use the PHP array\_pop() function You can use the PHP array\_pop() function to remove an element or value from the end of an array. The array\_pop() function also returns the last value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL. Let’s check out an example to understand how this function basically works: ```php <?php $sports = array("Baseball", "Cricket", "Football", "Shooting"); // Deleting last array item $removed = array_pop($sports); print_r($sports); echo "<br>"; var_dump($removed); ?> ``` ## 如何从 PHP 数组中删除第一个元素 ### Answer: Use the PHP array\_shift() function You can use the PHP array\_shift() function to remove the first element or value from an array. The array\_shift() function also returns the removed value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL. Let’s try out the following example to understand how this method works: ```php <?php $hobbies = array("Acting", "Drawing", "Music", "Films", "Photography"); // Deleting first array item $removed = array_shift($hobbies); print_r($hobbies); echo "<br>"; var_dump($removed); ?> ``` ## 如何在 PHP 中为数组的开头添加元素 ### Answer: Use the PHP array\_unshift() function You can use the PHP array\_unshift() function to insert one or more elements or values to the beginning of an array. Let’s check out an example to see how it works: ```php <?php $skills = array("HTML5", "CSS3", "JavaScript"); // Prepend array with new items array_unshift($skills, "Illustrator", "Photoshop"); print_r($skills); ?> ``` ## 如何在 PHP 中为数组的末尾添加元素 ### Answer: Use the PHP array\_push() function You can use the PHP array\_push() function to insert one or more elements or values at the end of an array. Let’s try out an example and see how this function works: ```php <?php $skills = array("HTML5", "CSS3", "JavaScript"); // Append array with new items array_push($skills, "jQuery", "PHP"); print_r($skills); ?> ``` ## 如何在 PHP 中把两个或多个数组合并成一个数组 ### Answer: Use the PHP array\_merge() function You can use the PHP array\_merge() function to merge the elements or values of two or more arrays together into a single array. The merging is occurring in such a way that the values of one array are appended to the end of the previous array. Let’s check out an example: ```php <?php $array1 = array(1, "fruit" => "banana", 2, "monkey", 3); $array2 = array("a", "b", "fruit" => "apple", "city" => "paris", 4, "c"); // Merging arrays together $result = array_merge($array1, $array2); print_r($result); ?> ``` > Note: If the input arrays contain the same string keys, then the later value for that key will overwrite the previous one during the merging process. ## 如何在 PHP 中按字母顺序对数组值排序 ### Answer: Use the PHP sort() and rsort() function The PHP sort() and rsort() functions can be used for sorting [numeric or indexed arrays](http://www.bixiaguangnian.com/manual/php7/3974.html "numeric or indexed arrays"). The following sections will show you how these functions basically work: ### Sorting Numeric Arrays in Ascending Order You can use the sort() function for sorting the numeric array elements or values alphabetically or numerically in the ascending order. Let’s try out an example to see how it works: ```php <?php $text = array("Sky", "Cloud", "Birds", "Rainbow", "Moon"); $numbers = array(1, 2, 3.5, 5, 8, 10); // Sorting the array of string sort($text); print_r($text); echo "<br>"; // Sorting the array of numbers sort($numbers); print_r($numbers); ?> ``` ### Sorting Numeric Arrays in Descending Order You can use the rsort() function for sorting the numeric array elements or values alphabetically or numerically in the descending order. Let’s check out an example: ```php <?php $text = array("Sky", "Cloud", "Birds", "Rainbow", "Moon"); $numbers = array(1, 2, 3.5, 5, 8, 10); // Sorting the array of string rsort($text); print_r($text); echo "<br>"; // Sorting the array of numbers rsort($numbers); print_r($numbers); ?> ``` ## 如何在 PHP 中删除数组中的重复值 ### Answer: Use the PHP array\_unique() function You can use the PHP array\_unique() function to remove the duplicate elements or values form an array. If the array contains the string keys, then this function will keep the first key encountered for every value, and ignore all the subsequent keys. Here’s an example: ```php <?php $array = array("a" => "moon", "star", "b" => "moon", "star", "sky"); // Deleting the duplicate items $result = array_unique($array); print_r($result); ?> ``` ## 如何在 PHP 中随机调整数组的顺序 ### Answer: Use the PHP shuffle() function You can use the PHP shuffle() function to randomly shuffle the order of the elements or values in an array. The shuffle() function returns FALSE on failure. Let’s try out the following example to understand how this function basically works: ```php <?php // Creating an array containing a range of elements $numbers = range(1, 10); // Randomize the order of array items shuffle($numbers); foreach ($numbers as $value){ echo "$value" . "<br>"; } ?> ``` ## 如何在 PHP 中比较两个数组的值 ### Answer: Use the PHP array\_diff() function You can use the PHP array\_diff() function to compare an array against one or more other arrays. The array\_diff() function returns the values in the first array that are not present in any of the other arrays. Let’s try out an example to understand how it actually works: ```php <?php $array1 = array("a" => "sky", "star", "moon", "cloud", "moon"); $array2 = array("b" => "sky", "sun", "moon"); // Comparing the values $result = array_diff($array1, $array2); print_r($result); ?> ``` ## 如何在 PHP 中计算数组中数值的总和 ### Answer: Use the PHP array\_sum() function You can use the PHP array\_sum() function to calculate the sum of all the numeric values in an array. Let’s try out the following example to understand how this function basically works: ```php <?php $array1 = array(1, 2, 4.5, 8, 15); $array2 = array("a" => 1.5, "b" => 2.5, "c" => 4.6, "d" => 10.4); echo array_sum($array1); // Outputs: 30.5 echo "<br>"; echo array_sum($array2); // Outputs: 19 ?> ``` ## 如何在 PHP 中删除数组中的空值 ### Answer: Use the PHP array\_filter() function You can simply use the PHP array\_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function. However, if no callback function is specified, all empty entries of array will be removed, such as “” (an empty string), 0 (0 as an integer), 0.0(0 as a float), "0" (0 as a string), NULL, FALSE and array() (an empty array). Let’s try out an example to understand how it actually works: ```php <?php $array = array("apple", "", 0, 2, null, -5, "0", "orange", 10, false); var_dump($array); echo "<br>"; // Filtering the array $result = array_filter($array); var_dump($result); ?> ``` In the above example the values 0 and "0" are also removed from the array. If you want to keep them, you can define a callback function as shown in the following example: ```php <?php $array = array("apple", "", 0, 2, null, -5, "0", "orange", 10, false); var_dump($array); echo "<br>"; // Defining a callback function function myFilter($var){ return ($var !== NULL && $var !== FALSE && $var !== ""); } // Filtering the array $result = array_filter($array, "myFilter"); var_dump($result); ?> ``` The callback function myFilter() is called for each element of the array. If myFilter() returns TRUE, then that element will be appended to the result array, otherwise not. ## 如何在 PHP 中用数组值填充下拉列表 ### Answer: Use the PHP foreach loop You can simply use the PHP [foreach loop](http://www.bixiaguangnian.com/manual/php7/3976.html "foreach loop") to create or populate HTML <select> box or any dropdown menu form the values of an array. Let’s try out an example and see how it works: ```php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Dynamically Generate Select Dropdowns</title> </head> <body> <form> <select> <option selected="selected">Choose one</option> <?php // A sample product array $products = array("Mobile", "Laptop", "Tablet", "Camera"); // Iterating through the product array foreach($products as $item){ echo "<option value='strtolower($item)'>$item</option>"; } ?> </select> <input type="submit" value="Submit"> </form> </body> </html> ``` ## 如何在 PHP 中获取关联数组的所有键值 ### Answer: Use the PHP array\_keys() function You can use the PHP array\_keys() function to get all the keys out of an associative array. Let’s try out an example to understand how this function works: ```php <?php $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York"); // Get keys from cities array print_r(array_keys($cities)); ?> ``` You can also use the PHP [foreach loop](http://www.bixiaguangnian.com/manual/php7/3976.html "foreach loop") to find or display all the keys, like this: ```php <?php $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York"); // Loop through cities array foreach($cities as $key => $value) { echo $key . " : " . $value . "<br>"; } ?> ``` ## 如何在 PHP 中获取关联数组的所有值 ### Answer: Use the PHP array\_values() function You can use the PHP array\_values() function to get all the values of an associative array. Let’s try out an example to understand how this function works: ```php <?php $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York"); // Get values from cities array print_r(array_values($cities)); ?> ``` You can also use the PHP [foreach loop](http://www.bixiaguangnian.com/manual/php7/3976.html "foreach loop") to find or display all the values, like this: ```php <?php $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York"); // Loop through cities array foreach($cities as $key => $value){ echo $key . " : " . $value . "<br>"; } ?> ``` ## 如何在 PHP 中按键对关联数组排序 ### Answer: Use the PHP ksort() and krsort() function The PHP ksort() and krsort() functions can be used for sorting an array by key. The following section will show you how these functions basically work. ### Sorting Associative Arrays in Ascending Order You can use the ksort() function for sorting an associative array by key alphabetically in the ascending order, while maintaining the relationship between key and data. ```php <?php $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat"); // Sorting the array by key ksort($fruits); print_r($fruits); ?> ``` ### Sorting Associative Arrays in Descending Order You can use the krsort() function for sorting an associative array by key alphabetically in the descending order, while maintaining the relationship between key and data. ```php <?php $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat"); // Sorting the array by key krsort($fruits); print_r($fruits); ?> ``` ## 如何在 PHP 中按值对关联数组排序 ### Answer: Use the PHP asort() and arsort() function The PHP asort() and arsort() functions can be used for sorting an array by value. The following section will show you how these functions basically work. ### Sorting Associative Arrays in Ascending Order You can use the asort()function for sorting an associative array by value alphabetically in the ascending order, while maintaining the relationship between key and data. ```php <?php $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat"); // Sorting the array by value asort($fruits); print_r($fruits); ?> ``` ### Sorting Associative Arrays in Descending Order You can use the arsort() function for ssorting an associative array by value alphabetically in the descending order, while maintaining the relationship between key and data. ```php <?php $fruits = array("b"=>"banana", "a"=>"apple", "d"=>"dog", "c"=>"cat"); // Sorting the array by value arsort($fruits); print_r($fruits); ?> ``` ## 如何在 PHP 中从数组中获取单个值 ### Answer: Use the Array Key or Index If you want to access an individual value form an indexed, associative or multidimensional array you can either do it through using the array index or key. Let's check out the following example to understand how it basically works: ```php <?php // Indexed array $sports = array("Baseball", "Cricket", "Football", "Shooting"); // Associative array $cities = array("France"=>"Paris", "India"=>"Mumbai", "UK"=>"London", "USA"=>"New York"); // Multidimensional array $superheroes = array( array( "name" => "Peter Parker", "character" => "Spider-Man", ), array( "name" => "Tony Stark", "character" => "Iron-Man", ), array( "name" => "Clark Kent", "character" => "Super-Man", ) ); echo $sports[0]; // Outputs: Baseball echo "<br>"; echo $sports[1]; // Outputs: Cricket echo "<br>"; echo $cities["France"]; // Outputs: Paris echo "<br>"; echo $cities["USA"]; // Outputs: New York echo "<br>"; echo $superheroes[0]["name"]; // Outputs: Peter Parker echo "<br>"; echo $superheroes[1]["character"]; // Outputs: Iron-Man ?> ``` ## 如何在 PHP 中循环浏览多维数组 ### Answer: Use the PHP nested loop You can simply use the [foreach loop](http://www.bixiaguangnian.com/manual/php7/3976.html "foreach loop") in combination with the [for loop](http://www.bixiaguangnian.com/manual/php7/3976.html#h2-php-for-loop "for loop") to access and retrieve all the keys, elements or values inside a multidimensional array in PHP. Let’s take a look at the following example to understand how it basically works: ```php <?php // Multidimensional array $superheroes = array( "spider-man" => array( "name" => "Peter Parker", "email" => "peterparker@mail.com", ), "super-man" => array( "name" => "Clark Kent", "email" => "clarkkent@mail.com", ), "iron-man" => array( "name" => "Harry Potter", "email" => "harrypotter@mail.com", ) ); // Printing all the keys and values one by one $keys = array_keys($superheroes); for($i = 0; $i < count($superheroes); $i++) { echo $keys[$i] . "{<br>"; foreach($superheroes[$keys[$i]] as $key => $value) { echo $key . " : " . $value . "<br>"; } echo "}<br>"; } ?> ``` ## 如何在 PHP 中从数组中删除元素 ### Answer: Use the PHP unset() Function If you want to delete an element from an array you can simply use the unset() function. The following example shows how to delete an element from an associative array and numeric array. ```php <?php $arr1 = array("a" => "Apple", "b" => "Ball", "c" => "Cat"); unset($arr1["b"]); // RESULT: array("a" => "Apple", "c" => "Cat") $arr2 = array(1, 2, 3); unset($arr2[1]); // RESULT: array(0 => 1, 2 => 3) ?> ``` If you see the above example carefully you will find that the unset() function didn’t reindex the array after deleting the value from the numeric array (line no-8). To fix this you can use the array\_splice() function. It takes three parameters: an array, offset (where to start), and length (number of elements to be removed). Let’s see how it actually works: ```php <?php $arr = array(1, 2, 3); array_splice($arr, 1, 1); // RESULT: array(0 => 1, 1 => 3) ?> ``` Last modification:September 18, 2024 © Allow specification reprint Like 如果觉得我的文章对你有用,请随意赞赏