note 46780 deleted from function.array-combine by aidan
| From: | aidan@php.net | Date: | Sat, 22 Jan 2005 12:22:52 +0000 |
| Subject: | note 46780 deleted from function.array-combine by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-83775@lists.php.net to get a copy of this message | ||
Note Submitter: m71 at free dot fr
----
much shorter and more efficient:
<?php if (!function_exists('array_combine')){
function array_combine($a,$b) {
if (count($a)!=count($b)) return FALSE;
foreach($a as $key) list(,$c[$key])=each($b);
return $c;
}}
$a=array( 1=>"a",0=>NULL,NULL=>0,"b"); next($a);next($a);
$b=array( "b", 0, NULL,array()); next($b);
var_dump(array_combine($a,$b));
?>
yields:
array(4) { ["a"]=> string(1) "b" [""]=> int(0) [0]=> NULL
["b"]=> array(0) { } }
The weird keys in $a make that constructions using current() or next() would not work
(recall btw. that a NULL key is treated by PHP as empty string).
I added the 'next()' in the above to show that reset($b) is not needed.
Note that the above returns NULL if $a,$b are empty. If you prefer,
add "$c=array();" before "foreach" [to get a more logical result]
or "!count($a) or " after "if (" [to imitate the PHP5 function].