note 57123 deleted from function.array-change-key-case by nlopess

From: Date: Sat, 24 Sep 2005 19:19:05 +0000
Subject: note 57123 deleted from function.array-change-key-case by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-95721@lists.php.net to get a copy of this message
Note Submitter: ipoller at gmail dot com ---- As you know, you can change the key case of an array with array_change_key_case easily, but if you want to invert case or change the key case to capitalize, the default action can't do it. so, you can try this custom function for php array_change_key_case! <?php /** * @source http://www.ipoll.cn/?op=ViewArticle&articleId=364&blogId=1 * @blog http://www.ipoll.cn/ * @author freish chilly * @email ipoller at gmail dot net (change "net" to "com") * @param case: 1->UPPER CASE 2->lower case 3->iNvErT CaSe 4->Capitalize **/ function custom_array_change_key_case( $array = array() , $case = 1 ) { switch ( $case ) { case 1: # UPPER CASE return array_change_key_case( $array , CASE_UPPER ); break; case 2: # LOWER CASE return array_change_key_case( $array, CASE_LOWER ); break; case 3: # INVERT CASE foreach ( $array as $key=>$val ) { $key_converted = ""; $tmp = preg_split("//",$key); @array_shift($tmp); @array_pop($tmp); foreach ($tmp as $letter) { if (preg_match("/[a-z]{1}/",$letter)) { $key_converted .= strtoupper( $letter ); } else if (preg_match("/[A-Z]{1}/",$letter)) { $key_converted .= strtolower( $letter ); } else { $key_converted .= $letter; } } $array_inverted[$key_converted] = $val; } return $array_inverted; break; case 4: # CAPITALIZE foreach ( $array as $key=>$val ) { $array_capitalized[ucfirst(strtolower($key))] = $val; } return $array_capitalized; break; } } $array = array("abc"=>1234,"DeS" => 34234, "fSD" => 3233); print_r(custom_array_change_key_case($array,3)); ?> Content-type: text/html X-Powered-By: PHP/4.3.10 Array ( [ABC] => 1234 [dEs] => 34234 [Fsd] => 3233 )

« previous php.notes (#95721) next »