note 34749 modified in function.array-flip by danbrown

From: Date: Fri, 14 May 2010 15:04:32 +0000
Subject: note 34749 modified in function.array-flip by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-169253@lists.php.net to get a copy of this message
I know a lot of people want a function to remove a key by value from an array. I saw solutions that iterate(!) though the whole array comparing value by value and then unsetting that value's key. PHP has a built-in function for pretty much everything (heard it will even cook you breakfast), so if you think "wouldn't it be cool if PHP had a function to do that...", odds are it already has. Check out this example. It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array. <?php $arr = array(11,12,13,12); // sample array $arr = array_flip($arr); unset($arr[12]); $arr = array(array_keys($arr)); ?> $arr contains: Array ( [0] => Array ( [0] => 11 [1] => 13 ) ?> ) --was-- I know a lot of people want a function to remove a key by value from an array. I saw solutions that iterate(!) though the whole array comparing value by value and then unsetting that value's key. PHP has a built-in function for pretty much everything (heard it will even cook you breakfast), so if you think "wouldn't it be cool if PHP had a function to do that...", odds are it already has. Check out this example. It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array. <?php $arr = array(11,12,13,12); // sample array $arr = array_flip($arr); unset($arr[12]); $arr = array(array_keys($arr)); ?> $arr contains: <?php Array ( [0] => Array ( [0] => 11 [1] => 13 ) ?> ) http://php.net/manual/en/function.array-flip.php

« previous php.notes (#169253) next »