In the previous article, we introduced the method of emptying and deduplicating arrays, that is, deleting empty elements and duplicate elements in the array. If you are interested, you can click on the link to read → " How to remove blanks in PHP array learning Or repeated elements》. This time we continue the study and practice of PHP arrays and talk about how to filter arrays and extract numerical elements.
→Related recommendations: 《PHP array learning series summary (continuously updated~)》
The main content of today’s article is: Utilization PHP to filter the array, filter out the numeric elements (numeric values or numeric strings), and then combine them into a new array and return it.
Below we will introduce two implementation methods to you. First, we will start with the familiar method "foreach loop", and then introduce a method of filtering arrays using PHP's built-in functions.
Method 1: Use the foreach statement
<?php $array = array("php", 11, '', 12, "PHP中文网",13,"green",2021,"mysql","14",15); foreach($array as $value){ if(is_numeric($value)){ $result[]=$value; } } var_dump($result); ?>
Analyze the code:
Use the foreach statement to traverse the array, in each loop Assign the key value to $value
;
Use the is_numeric()
function to detect $value
Whether it is a number or a string of numbers;
If it is a number or a string of numbers, store $value
in the $results
array .
In this way, all the numeric elements in the $results array are the numeric elements in the $array array. Using var_dump($result)
, the output result is:
Method 2: Using the array_filter() function
In the previous article, we already know that the array_filter() function can use a callback function To filter the elements in the array, the array elements will be passed to the callback function for processing.
Give the implementation code directly:
<?php $array = array("php", 11, '', 12, "PHP中文网",13,"green",2021,"mysql","14",15); function filter_number($value){ if(is_numeric($value)){ return TRUE; } } $result=array_filter($array,"filter_number"); var_dump($result); ?>
The output result is:
Let’s take a look at the array_filter() function
# The ##array_filter() function iterates through each value in the array and passes each key value to a user-defined function or callback function; if the callback function returns true, the current key value in the input array is returned to the result array ( The array key names remain unchanged). The syntax format is:array_filter ($array , function callbackfn ($value[, $key]),$mode)
function callbackfn ($value[, $key]): Callback function, which can be omitted; if the callback function is omitted, null values will be filtered by default.
PHP function array array function video explanation, come and learn!
The above is the detailed content of PHP array learning: extract digital elements and splice them into a new array. For more information, please follow other related articles on the PHP Chinese website!