PHP Doku:: Ändert alle Schlüssel in einem Array - function.array-change-key-case.html

Verlauf / Chronik / History: (16) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenArraysArray Funktionenarray_change_key_case

Ein Service von Reinhard Neidl - Webprogrammierung.

Verdiene Geld mit Deiner Homepage oder deinem Blog: Setzte eine Textlinkwerbung und bestimme den Preis selber.
Einfach kostenlos anmelden und einen Platz auf Deiner Homepage anbieten.
Make money with your homepage or blog: Set a text link advertising and declare the price.
Register free of charge and offer a place on your homepage.
Array Funktionen

<<Array Funktionen

array_chunk>>

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5)

array_change_key_caseÄndert alle Schlüssel in einem Array

Beschreibung

array array_change_key_case ( array $input [, int $case = CASE_LOWER ] )

Gibt ein Array zurück, in dem alle Schlüssel aus input in Klein- oder Großbuchstaben umgewandelt wurden. Numerische Indizes werden nicht geändert.

Parameter-Liste

input

Das Eingabe-Array

case

Entweder CASE_UPPER oder CASE_LOWER (Standard)

Rückgabewerte

Gibt ein Array zurück, dessen Schlüssel in Klein- oder Großbuchstaben umgewandelt wurden, oder FALSE, wenn input kein Array ist.

Fehler/Exceptions

Wirft E_WARNING, wenn input kein Array ist.

Beispiele

Beispiel #1 array_change_key_case()-Beispiel

<?php
$input_array 
= array("FirSt" => 1"SecOnd" => 4);
print_r(array_change_key_case($input_arrayCASE_UPPER));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

Anmerkungen

Hinweis:

Hat ein Array Indizes, die nach einem Durchlauf durch diese Funktion gleich sind (z.B. "keY" und "kEY"), überschreibt der spätere Wert im Array andere Indizes.


Verdiene Geld mit Deiner Homepage oder deinem Blog: Setzte eine Textlinkwerbung und bestimme den Preis selber.
Einfach kostenlos anmelden und einen Platz auf Deiner Homepage anbieten.
Make money with your homepage or blog: Set a text link advertising and declare the price.
Register free of charge and offer a place on your homepage.
11 BenutzerBeiträge:
- Beiträge aktualisieren...
Lus Henrique Pessoa
24.09.2010 18:03
<?php

// improving the previous script
function ack_r3(&$array, $case=CASE_LOWER, $flag_rec=false)
    {
     
$array = array_change_key_case($array, $case);
      if (
$flag_rec ) {
        foreach (
$array as $key => $value) {
            if (
is_array($value) ) {
               
ack_r3($array[$key], $case, true);
            }
        }
      }
    }

// same of array_change_key_case
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
   
ack_r3($arr, CASE_LOWER,false);
   
var_dump($arr);
   
   
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
   
ack_r3($arr, CASE_LOWER,true);
   
var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["PHONE"]=>
    string(9) "3010-7148"
    ["E-MAIL"]=>
    string(12) "luis@net.com"
  }
}
array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
Luis Henrique Pessoa
23.09.2010 18:25
Script to change case of sub-arrays keys:

<?php

   
function arrKey2Lower(&$arrVals) {
        foreach(
$arrVals as $key => $item ) {
           
$key2 = strtolower($key);
            if (
$key2 != $key) {
                unset(
$arrVals[$key]);
               
$arrVals[$key2]=$item;
               
$key=$key2;
            }
           
            if (
is_array($item) ) { arrKey2Lower($arrValores[$key]); }
        }
    }
   
   
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
   
arrKey2Lower($arr);
   
var_dump($arr);
   
   
?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
info at microweb dot lt
29.11.2009 11:07
Simple function to change multidimensional array's all values to uppercase. If you would like to change to lowercase then change "mb_strtoupper" to  "mb_strtolower". It works perfect for me ;)

<?php
function change_case_recursive($arr){
    foreach (
$arr as $key=>$val){
        if (!
is_array($arr[$key])){
           
$arr[$key]=mb_strtoupper($arr[$key]);
        }else{
           
$arr[$key]=change_case_recursive($arr[$key]);
        }
    }
    return
$arr;   
}
?>
david at ramaboo dot com
2.02.2009 12:22
Same as array_change_key_case only with the values. This should really be part of PHP!

<?php
/**
 * @brief Returns an array with all values lowercased or uppercased.
 * @return array Returns an array with all values lowercased or uppercased.
 * @param object $input The array to work on
 * @param int $case [optional] Either \c CASE_UPPER or \c CASE_LOWER (default).
 */
function array_change_value_case(array $input, $case = CASE_LOWER) {
    switch (
$case) {
        case
CASE_LOWER:
            return
array_map('strtolower', $input);
            break;
        case
CASE_UPPER:
            return
array_map('strtoupper', $input);
            break;
        default:
           
trigger_error('Case is not valid, CASE_LOWER or CASE_UPPER only', E_USER_ERROR);
            return
false;
    }
}
?>
charles
13.01.2009 8:38
<?php
$input_array
= array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>
anon at ymous dot com
2.12.2008 12:19
Below is a recursive version of this function.

<?php
   
/**
     * A recursive array_change_key_case function.
     * @param array $input
     * @param integer $case
     */
   
function array_change_key_case_recursive($input, $case = null){
        if(!
is_array($input)){
           
trigger_error("Invalid input array '{$array}'",E_USER_NOTICE); exit;
        }
       
// CASE_UPPER|CASE_LOWER
       
if(null === $case){
           
$case = CASE_LOWER;
        }
        if(!
in_array($case, array(CASE_UPPER, CASE_LOWER))){
           
trigger_error("Case parameter '{$case}' is invalid.", E_USER_NOTICE); exit;
        }
       
$input = array_change_key_case($input, $case);
        foreach(
$input as $key=>$array){
            if(
is_array($array)){
               
$input[$key] = array_change_key_case_recursive($array, $case);
            }
        }
        return
$input;
    }
?>
andreas dot schuhmacher87 at googlemail dot com
15.04.2008 3:01
multibyte and multi-dimensional-array support, have fun!

<?php
    define
('ARRAY_KEY_FC_LOWERCASE', 25); //FOO => fOO
   
define('ARRAY_KEY_FC_UPPERCASE', 20); //foo => Foo
   
define('ARRAY_KEY_UPPERCASE', 15); //foo => FOO
   
define('ARRAY_KEY_LOWERCASE', 10); //FOO => foo
   
define('ARRAY_KEY_USE_MULTIBYTE', true); //use mutlibyte functions
   
    /**
    * change the case of array-keys
    *
    * use: array_change_key_case_ext(array('foo' => 1, 'bar' => 2), ARRAY_KEY_UPPERCASE);
    * result: array('FOO' => 1, 'BAR' => 2)
    *
    * @param    array
    * @param    int
    * @return     array
    */
   
function array_change_key_case_ext(array $array, $case = 10, $useMB = false, $mbEnc = 'UTF-8') {
       
$newArray = array();
       
       
//for more speed define the runtime created functions in the global namespace
       
        //get function
       
if($useMB === false) {
           
$function = 'strToUpper'; //default
           
switch($case) {
               
//first-char-to-lowercase
               
case 25:
                   
//maybee lcfirst is not callable
                   
if(!function_exists('lcfirst'))
                       
$function = create_function('$input', '
                            return strToLower($input[0]) . substr($input, 1, (strLen($input) - 1));
                        '
);
                    else
$function = 'lcfirst';
                    break;
               
               
//first-char-to-uppercase               
               
case 20:
                   
$function = 'ucfirst';
                    break;
               
               
//lowercase
               
case 10:
                   
$function = 'strToLower';
            }
        } else {
           
//create functions for multibyte support
           
switch($case) {
               
//first-char-to-lowercase
               
case 25:
                   
$function = create_function('$input', '
                        return mb_strToLower(mb_substr($input, 0, 1, \''
. $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \''
. $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    '
);
                   
                    break;
               
               
//first-char-to-uppercase
               
case 20:
                   
$function = create_function('$input', '
                        return mb_strToUpper(mb_substr($input, 0, 1, \''
. $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \''
. $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    '
);
                   
                    break;
               
               
//uppercase
               
case 15:
                   
$function = create_function('$input', '
                        return mb_strToUpper($input, \''
. $mbEnc . '\');
                    '
);
                    break;
               
               
//lowercase
               
default: //case 10:
                   
$function = create_function('$input', '
                        return mb_strToLower($input, \''
. $mbEnc . '\');
                    '
);
            }
        }
       
       
//loop array
       
foreach($array as $key => $value) {
            if(
is_array($value)) //$value is an array, handle keys too
               
$newArray[$function($key)] = array_change_key_case_ex($value, $case, $useMB);
            elseif(
is_string($key))
               
$newArray[$function($key)] = $value;
            else
$newArray[$key] = $value; //$key is not a string
       
} //end loop
       
       
return $newArray;
    }
?>
dot dot dot dot dot alexander at gmail dot com
30.01.2008 18:22
Basically this is the function if your version is lower than 4.2.0
<?php
if ( !defined('CASE_LOWER') )define('CASE_LOWER', 0);
if ( !
defined('CASE_UPPER') )define('CASE_UPPER', 1);

if(!
function_exists("array_change_key_case")){
    function
array_change_key_case($input, $case=0){
        if(!
is_array($input))return FALSE;
       
$product = array();
        foreach(
$input as $key => $value){
            if(
$case){ //Upper
               
$key2 = (  (is_string($key)) ? (strtoupper($key)) : ($key)  );
               
$product[$key2] = $value;
            }
            else{
//Lower
               
$key2 = (  (is_string($key)) ? (strtolower($key)) : ($key)  );
               
$product[$key2] = $value;
            }
        }
        return
$product;
    }
/* endfunction array_change_key_case */
}/* endfunction exists array_change_key_case*/
?>
john at doe dot com
26.09.2007 9:04
<?php
function array_change_value_case($input, $case = CASE_LOWER)
{
   
$aRet = array();
   
    if (!
is_array($input))
    {
        return
$aRet;
    }
   
    foreach (
$input as $key => $value)
    {
        if (
is_array($value))
        {
           
$aRet[$key] = array_change_value_case($value, $case);
            continue;
        }
       
       
$aRet[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
    }
   
    return
$aRet;
}
?>
cm at gameswelt dot de
10.08.2007 13:11
I just changed the code a little bit so you havent got a code that repeats itself.

<?php

function array_change_key_case_secure($array = array(), $case = CASE_UPPER){
   
$secure = array();
   
$functionWrap = array(CASE_UPPER => 'strtoupper',
                           
CASE_LOWER => 'strtolower');
                           
    foreach(
$array as $key => $val){
        if(isset(
$functionWrap[$key])){
           
$key = $functionWrap[$case]($key);
           
$secure[$key][] = $val;
        } else {
            die(
'Not a known Type');
        }
    }
   
    foreach(
$secure as $key => $val){
        if(
count($secure[$key]) == 1){
           
$secure[$key] = $val[0];
        }
    }
   
    return
$secure;
}

$myArray = array('A' => 'Hello',
                   
'B' => 'World',
                   
'a' => 'how are you?');

print_r($myArray);
$myArray = array_change_key_case_secure($myArray);
print_r($myArray);

/*
Array
(
    [A] => Hello
    [B] => World
    [a] => how are you?
)
Array
(
    [A] => Array
        (
            [0] => Hello
            [1] => how are you?
        )

    [B] => World
)
*/
aidan at php dot net
2.06.2004 5:06
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)