Home  >  Article  >  Backend Development  >  How to use key to remove specified elements from an array in php

How to use key to remove specified elements from an array in php

WBOY
WBOYOriginal
2022-03-25 18:46:222069browse

Method: 1. Use "array_keys(array)" to return a new array containing the array key name; 2. Use "array_search(key, new array)" to return the key name of the specified key in the new array; 3. . Use "array_splice(array, specified key name, 1)" to remove the specified element.

How to use key to remove specified elements from an array in php

The operating environment of this article: Windows 10 system, PHP version 7.1, Dell G3 computer.

How to use key in php to remove specified elements from an array

First use the array_keys function and array_search function to obtain the position of the specified key in the array

Then use the array_splice function to delete Just specify the element.

Detailed introduction:

array_keys() function returns a new array containing all the key names in the array.

If the second parameter is provided, only the key name with the key value is returned.

array_search() function searches for a key value in the array and returns the corresponding key name.

array_splice() function removes the selected element from an array and replaces it with a new element. This function will also return the array containing the removed elements.

The example is as follows:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
$b=array_keys($a);
$c=array_search("b",$b);
array_splice($a, $c, 1);
print_r($a);
?>

Output result:

How to use key to remove specified elements from an array in php

Recommended learning: "PHP video tutorial

The above is the detailed content of How to use key to remove specified 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