$v){//loop body}" to loop through the array; 2. In the loop body, use "if(is_array($v)){unset( $arr[$k]);}" Determine whether the array element "$v" is an array type, and if so, delete the element."/> $v){//loop body}" to loop through the array; 2. In the loop body, use "if(is_array($v)){unset( $arr[$k]);}" Determine whether the array element "$v" is an array type, and if so, delete the element.">

Home >Backend Development >PHP Problem >How to remove array elements from an array in php

How to remove array elements from an array in php

青灯夜游
青灯夜游Original
2022-06-02 19:28:212582browse

Removal method: 1. Use "foreach($arr as $k=>$v){//loop body}" to loop through the array; 2. In the loop body, use "if(is_array( $v)){unset($arr[$k]);}" Determine whether the array element "$v" is an array type, and if so, delete the element.

How to remove array elements from an array in php

The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer

php removes an array Method of array elements

Step 1. Use foreach to traverse the array

foreach ($arr as $k => $v){
    //循环体语句块;
}

Traverse the given $arr array, in each loop The value of the current array will be assigned to $v, and the key name will be assigned to $k.

Step 2. In the loop body, determine whether the array element $v is an array type. If so, delete the element

if(is_array($v)){
    unset($arr[$k]);
}
  • is_array() function is used to detect whether a variable is an array. Returns TRUE if the variable being examined is an array, otherwise FALSE.

  • $Array variable name [key name] Can access specific array elements

  • unset() function is used for destruction given variable.

Implementation code:

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr=array(1,array(2,3),-5,21,array(4,array(2,3)));
var_dump($arr);
foreach($arr as $k=>$v){
if(is_array($v)){
	unset($arr[$k]);
}
}
var_dump($arr);
?>

How to remove array elements from an array in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to remove array elements from an array in php. For more information, please follow other related articles on the PHP Chinese website!

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