Home  >  Article  >  Backend Development  >  PHP array operations

PHP array operations

高洛峰
高洛峰Original
2016-10-21 09:59:56973browse

Method 1:

<?PHP
$array = array(1,2,4,6,8);
echo end($array);
?>

Output

//输出8

Method 2:

<?PHP
$array = array(1,2,4,6,8);
echo array_pop($array);
?>

Output

//输出8


Method 3:

<?PHP
$array = array(1,2,4,6,8);
$k = array_slice($array,-1,1);
print_r($k);  //结果是一维数组
?>

Output

Array ( [0] => 8 )



The second method has a drawback. The Array_pop() function will "take out" the last number of the original data, which is equivalent to cutting. It turns out There will no longer be a last value in the data. Re re:

<?PHP
$array = array(1,2,4,6,8);
array_pop($array);
print_r($array);
?>
E

Output:

Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 6 )



is a built -in function in PHP. In fact, we can also obtain the PHP array through some of the methods we write The last element in

<?php
$array = array(1,2,4,6,8);
$last = count($array);
echo $array[$last-1];
?>

🎜🎜🎜🎜Of course, if the built-in method can be implemented, we try to use PHP’s built-in function, because the built-in method is the most efficient in terms of efficiency and time, but then develop During the process, if we don't know the existence of this method or don't remember this method, we can also write the function method we want based on our own logic. 🎜🎜🎜🎜
Statement:
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