Home>Article>Backend Development> How to get certain values in an array in php
3 ways to obtain: 1. Use "$array name[subscript]" to obtain one by one. 2. Use array_slice() to get several consecutive element values, the syntax is "array_slice(array, starting position, number)" or "array_slice(array, - position)". 3. Use array_splice() to get several consecutive elements Element value, syntax "array_splice(array, starting position, number)" or "array_splice(array, - position)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php provides a variety of methods to get certain values in the array, let’s take a look below.
Situation 1: Get several discontinuous element values
In PHP, you can use the "$array name[subscript]
" statement to get them one by one.
"$array name[subscript]
" can access an element of the specified subscript in the array
"; echo "获取第3位的元素:".$arr[2]."
"; echo "获取第6位的元素:".$arr[5]."
"; ?>
Case 2: Get several consecutive element values
Method 1. Use array_slice() function
array_slice() function is PHP A function provided to intercept an array and extract a fragment from the array.
array_slice($array,$start,$length,$preserve)
This function supports 2 required parameters:$array
and$start
, two omitted parameters$length
and$preserve
.
Parameter$array
does not need to be introduced. , the parameter$start
is used to specify the position (subscript) to start interception, and the parameter$length
indicates the interception length (if omitted, it will intercept from the specified subscript to the end of the array ).
The output result is:
The parameter$start
can be a negative number, then the distance from the end of $array-Start at the position of
(that is, position from the right side of the array to the left according to the absolute value), and intercept from the back to the front. For example,-2
means starting from the penultimate element of the array .
The output result is:
2. Use array_splice() function
array_splice() function When deleting some elements of the array, the deleted elements will be formed into a new array, and then the new array will be returned.
Usearray_splice($array,$start,$length)
The function can intercept an array fragment of the specified length (the value of$length
) based on the array subscript (the value of$start
).
Let’s look at the following small example:
The output result is:
$start
If the value is negative, get the last N elements
Note:array_splice() function will change the original array.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to get certain values in an array in php. For more information, please follow other related articles on the PHP Chinese website!