note 93413 added to function.array-map

From: Date: Tue, 08 Sep 2009 22:20:47 +0000
Subject: note 93413 added to function.array-map
Groups: php.notes 
Request: Send a blank email to php-notes+get-160314@lists.php.net to get a copy of this message
I recently discovered that PHP has no loop-free manner for modifying the keys in an array. I was hoping to use a built-in function to prefix the keys. Having found no native function to do this, I threw together this monster: <?php function array_prefix_keys ( $a = array() , $p = ':' ) { return array_combine( array_map( create_function('$k,$p','return "$p{$k}";') , array_keys($a) , array_fill(0,count($a),$p) ) , array_values($a) ); } ?> It isn't very pretty, to be sure, but it does allow you to do this: <?php $array = array( 'id' => 1, 'title' => 'about-us', 'author' => 'Bill Brown', 'dated' => '2009-SEP-15' ); echo '<pre>',print_r($array,1),'</pre>'; $array = array_prefix_keys($array,"content_"); echo '<pre>',print_r($array,1),'</pre>'; ?> Which will give you this: Array ( [id] => 1 [title] => about-us [author] => Bill Brown [dated] => 2009-SEP-15 ) Array ( [content_id] => 1 [content_title] => about-us [content_author] => Bill Brown [content_dated] => 2009-SEP-15 ) Hope it helps! --Bill ---- Server IP: 208.69.120.35 Probable Submitter: 98.235.179.75 ---- Manual Page -- http://www.php.net/manual/en/function.array-map.php Edit -- https://master.php.net/note/edit/93413 Del: integrated -- https://master.php.net/note/delete/93413/integrated Del: useless -- https://master.php.net/note/delete/93413/useless Del: bad code -- https://master.php.net/note/delete/93413/bad+code Del: spam -- https://master.php.net/note/delete/93413/spam Del: non-english -- https://master.php.net/note/delete/93413/non-english Del: in docs -- https://master.php.net/note/delete/93413/in+docs Del: other reasons-- https://master.php.net/note/delete/93413 Reject -- https://master.php.net/note/reject/93413 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#160314) next »