php 数组删除特定元素
时间: 2023-07-06 20:37:33 浏览: 65
在 PHP 中,可以使用 unset 函数来删除数组中的特定元素。unset 函数可以接受一个或多个参数,每个参数都是一个数组元素的键名。当 unset 函数调用时,它会从数组中删除指定的键名及其对应的值。
下面是一个示例代码,删除数组中的特定元素:
```
$array = ['a' => 1, 'b' => 2, 'c' => 3];
unset($array['b']);
print_r($array);
```
输出结果为:
```
Array
(
[a] => 1
[c] => 3
)
```
可以看到,数组中键名为 'b' 的元素已经被删除了。你可以根据需要使用 unset 函数来删除其它特定元素。
相关问题
php 数组删除特定值的元素
在 PHP 中,可以使用 array_filter 函数来删除数组中特定值的元素。该函数会遍历数组中的每个元素,并根据指定的回调函数来决定是否保留该元素。
下面是一个示例代码,删除数组中值为 2 的元素:
```
$array = [1, 2, 3, 2, 4];
$array = array_filter($array, function($value) {
return $value !== 2;
});
print_r($array);
```
输出结果为:
```
Array
(
[0] => 1
[2] => 3
[4] => 4
)
```
可以看到,数组中值为 2 的元素已经被删除了。你可以根据需要修改回调函数来删除其它指定值的元素。
php两个数组中特定元素相加
可以使用循环遍历两个数组,将相同索引的元素相加并存储到一个新的数组中,例如:
```php
$array1 = array(1, 2, 3, 4);
$array2 = array(5, 6, 7, 8);
$result = array();
for ($i = 0; $i < count($array1); $i++) {
$result[] = $array1[$i] + $array2[$i];
}
print_r($result);
```
输出结果为:
```
Array
(
[0] => 6
[1] => 8
[2] => 10
[3] => 12
)
```
如果两个数组的长度不同,可以使用`count()`函数获取较短数组的长度作为循环次数。如果需要对特定的元素相加,可以在循环中加入判断条件。例如,对数组中索引为偶数的元素相加:
```php
$array1 = array(1, 2, 3, 4, 5);
$array2 = array(5, 6, 7, 8, 9);
$result = array();
for ($i = 0; $i < count($array1); $i++) {
if ($i % 2 == 0) { // 索引为偶数
$result[] = $array1[$i] + $array2[$i];
} else {
$result[] = $array1[$i];
}
}
print_r($result);
```
输出结果为:
```
Array
(
[0] => 6
[1] => 2
[2] => 10
[3] => 4
[4] => 5
)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)