Home >Backend Development >PHP Problem >What are the ways to get values from php arrays?
Methods to obtain values: 1. Use the "array_shift($arr)" statement; 2. Use the "array_pop($arr)" statement; 3. Use the "array_splice($arr, number of elements)" statement ;4. Use the "array_slice($arr, number of elements)" statement.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Get the value from the php array Method
Method 1: Use the array_shift() function to obtain the first element value in the array
<?php header("Content-type:text/html;charset=utf-8"); $arr= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); var_dump($arr); //获取数组中的第一个元素 $first = array_shift($arr); echo "数组的第一个元素为:".$first; ?>
Output result:
Method 2: Use the array_pop() function to get the last element value in the array
Let’s look at an example first:
<?php header("Content-type:text/html;charset=utf-8"); $arr= array("香蕉","苹果","梨子","橙子","橘子","榴莲"); var_dump($arr); //获取数组中的第一个元素 $first = array_pop($arr); echo "数组的最后一个元素为:".$first; ?>
Output result:
Method 3: Use the array_rand() function to randomly obtain multiple element values
<?php $arr=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); $rand = array_rand($arr,3); foreach($rand as $val){ $arr2[$val]=$arr[$val]; } var_dump($arr2); ?>
Output result:
Method 4: Use the array_splice() function to obtain multiple element values
<?php header("Content-type:text/html;charset=utf-8"); $arr = array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "截取的数组片段:"; $result = array_splice($arr,2); //截取从下标2开始的全部数组元素 var_dump($result); $arr = array(10,12,20,25,24); $result = array_splice($arr,1,2);//截取从下标1开始的两个元素 var_dump($result); ?>
The output result is:
Method 5: Use the array_slice() function to obtain multiple elements
<?php header("Content-type:text/html;charset=utf-8"); $arr = array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "截取的数组片段:"; $result = array_slice($arr,2); //截取从下标2开始的全部数组元素 var_dump($result); $result = array_slice($arr,1,2); //截取从下标1开始的两个元素 var_dump($result); ?>
Output The result is:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What are the ways to get values from php arrays?. For more information, please follow other related articles on the PHP Chinese website!