Php array keys to lowercase

array_change_key_case() function in PHP

The array_change_key_case returns an array with all keys in lowercase or uppercase. It returns an array with its keys in lowercase or uppercase. It returns FALSE if array is not an array.

Syntax

array_change_key_case(arr,case)

Parameters

  • arr − The array. Required.
  • case − Specify the case. The default is Lowercase i.e. CASE_LOWER. Optional.

Return

The array_change_key_case() function returns an array with its keys in lowercase or uppercase. It returns FALSE if array is not an array.

The following is an example to convert all keys to uppercase.

Example

"Bus","t"=>"Truck"); print_r(array_change_key_case($vehicle,CASE_UPPER)); ?>

Output

The following is an example to convert all keys to lowercase.

Example

"Car","T"=>"Bike"); print_r(array_change_key_case($vehicle,CASE_LOWER)); ?>

Output

Samual Sam

Learning faster. Every day.

  • Related Articles
  • filter_has_var() function in PHP
  • filter_id() function in PHP
  • filter_input() function in PHP
  • filter_input_array() function in PHP
  • filter_list() function in PHP
  • filter_var_array() function in PHP
  • filter_var() function in PHP
  • constant() function in PHP
  • define() function in PHP
  • defined() function in PHP
  • die() function in PHP
  • eval() function in PHP
  • exit() function in PHP
  • get_browser() function in PHP
  • highlight_file() function in PHP

Источник

array_change_key_case

Returns an array with all keys from array lowercased or uppercased. Numbered indices are left as is.

Читайте также:  System error java lang nullpointerexception

Parameters

Either CASE_UPPER or CASE_LOWER (default)

Return Values

Returns an array with its keys lower or uppercased, or null if array is not an array.

Examples

Example #1 array_change_key_case() example

$input_array = array( «FirSt» => 1 , «SecOnd» => 4 );
print_r ( array_change_key_case ( $input_array , CASE_UPPER ));
?>

The above example will output:

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

Notes

Note:

If an array has indices that will be the same once run through this function (e.g. » keY » and » kEY «), the value that is later in the array will override other indices.

User Contributed Notes 19 notes

function array_change_key_case_unicode ( $arr , $c = CASE_LOWER ) $c = ( $c == CASE_LOWER ) ? MB_CASE_LOWER : MB_CASE_UPPER ;
foreach ( $arr as $k => $v ) $ret [ mb_convert_case ( $k , $c , «UTF-8» )] = $v ;
>
return $ret ;
>

$arr = array( «FirSt» => 1 , «yağ» => «Oil» , «şekER» => «sugar» );
print_r ( array_change_key_case ( $arr , CASE_UPPER ));
print_r ( array_change_key_case_unicode ( $arr , CASE_UPPER ));
?>

Array
(
[FIRST] => 1
[YAğ] => Oil
[şEKER] => sugar
)
Array
(
[FIRST] => 1
[YAĞ] => Oil
[ŞEKER] => sugar
)

I improve the array_change_key_case_recursive function ,let it can lowercase or uppercase keys

function array_change_key_case_recursive($arr, $case = CASE_LOWER)
return array_map(function($item) use($case) if(is_array($item))
$item = array_change_key_case_recursive($item, $case);
return $item;
>,array_change_key_case($arr, $case));
>

Here is the most compact way to lower case keys in a multidimensional array

function array_change_key_case_recursive($arr)
return array_map(function($item) if(is_array($item))
$item = array_change_key_case_recursive($item);
return $item;
>,array_change_key_case($arr));
>

Improved multidimensional unicode func (after qeremy):
function array_change_key_case_unicode_recurs ( $arr , $c = CASE_LOWER ) foreach ( $arr as $k => $v ) $ret [ mb_convert_case ( $k , (( $c === CASE_LOWER ) ? MB_CASE_LOWER : MB_CASE_UPPER ), «UTF-8» )] = ( is_array ( $v ) ? array_change_key_case_unicode_recurs ( $v , $c ) : $v );
>
return $ret ;
>

$arr = array( «FirSt» => 1 , «ZażóŁć gęŚlą jaŹń» => array( «yağ» => «Oil» , «şekER» => «sugar» ) );
print_r ( array_change_key_case ( $arr , CASE_UPPER ));
print_r ( array_change_key_case_unicode_recurs ( $arr , CASE_UPPER ));
?>

Array
(
[FIRST] => 1
[ZAżóŁć GęŚLą JAŹń] => Array
(
[yağ] => Oil
[şekER] => sugar
)
)
Array
(
[FIRST] => 1
[ZAŻÓŁĆ GĘŚLĄ JAŹŃ] => Array
(
[YAĞ] => Oil
[ŞEKER] => sugar
)
)

Array of partitions with always the same number of sub-array indexes.

function partitionFixedSubArray ( $array , $length , $empty_space )
<
$result = [];

$result = array_chunk ( $array , $length );
$last_array_count = sizeof ( end ( $result ));

for ( $i = $last_array_count ; $i < $length ; $i ++) array_push ( $result [ key ( $result )], $empty_space );
>
>
>

$employees = [
«Paidi» ,
«Paijo» ,
«Darno» ,
«Kusnan» ,
«Mukidi» ,
«Sarno» ,
«Nurdin» ,
«Parmen» ,
«Sukinah» ,
«Sartini» ,
«Sukijan» ,
«Yono» ,
«Supoyo»
];

echo «

" ; 
print_r ( partitionFixedSubArray ( $employees , 5 , "empty space" ));
echo "

» ;

[1] => Array
(
[0] => Sarno
[1] => Nurdin
[2] => Parmen
[3] => Sukinah
[4] => Sartini
) [2] => Array
(
[0] => Sukijan
[1] => Yono
[2] => Supoyo
[3] => empty space
[4] => empty space
)

multibyte and multi-dimensional-array support, have fun!

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 . ‘\’);
‘ );

//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 . ‘\’);
‘ );

//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

/**
* Convert keys in an array.
*
* @param array $array Source data
* @param callable $callback Function name (strtolower, strtoupper, ucfirst, lcfirst, ucwords)
* @return array
*/
function array_convert_key_case (array $array , callable $callback = ‘strtolower’ )
return array_combine (
array_map ( $callback , array_keys ( $array )),
array_values ( $array )
);
>
?>

Below is a recursive version of this function.

/**
* 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 ;
>
?>

Use this to capitalize first letter of all array keys:

// Change key if needed
if ( $newKey != $key )
unset( $data [ $key ]);
$data [ $newKey ] = $value ;
>

// Handle nested arrays
if ( is_array ( $value ))
ucfirstKeys ( $data [ $key ]);
>
>
>

$test = array( ‘foo’ => ‘bar’ , ‘moreFoo’ => array( ‘more’ => ‘foo’ ));
ucfirstKeys ( $test );
print_r ( $test );

?>

Result:
Array ( [MoreFoo] => Array ( [More] => foo ) [Foo] => bar )

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 ));
>

Источник

PHP array_change_key_case() Function

The array_change_key_case() function changes all keys in an array to lowercase or uppercase.

Syntax

Parameter Values

  • CASE_LOWER — Default value. Changes the keys to lowercase
  • CASE_UPPER — Changes the keys to uppercase

Technical Details

Return Value: Returns an array with its keys in lowercase or uppercase, or FALSE if array is not an array
PHP Version: 4.2+

More Examples

Example

Change all keys in an array to lowercase:

Example

If two or more keys will be equal after running array_change_key_case() (e.g. «b» and «B»), the latest array will override the other:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Array_change_key_case()

The PHP Array Change Key Case function is a powerful tool for transforming the keys of an array from one case to another. Whether you need to change the keys of an array to all uppercase or all lowercase, the Array Change Key Case function makes it easy to do so.

How to Use the Array Change Key Case Function

The Array Change Key Case function is used as follows:

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

Where $array is the input array, and $case is an optional argument that specifies the desired case for the keys. The $case argument can be either CASE_LOWER (for lowercase keys) or CASE_UPPER (for uppercase keys). If the $case argument is omitted, the keys will be converted to lowercase by default.

Example Usage

Here is an example of using the Array Change Key Case function to convert the keys of an array to uppercase:

 $array = array("first_name" => "John", "last_name" => "Doe"); $newArray = array_change_key_case($array, CASE_UPPER); print_r($newArray); ?>

The output of this code will be:

Array ( [FIRST_NAME] => John [LAST_NAME] => Doe )

As you can see, the keys of the $array have been successfully converted to uppercase.

Benefits of Using the Array Change Key Case Function

Using the Array Change Key Case function offers several benefits, including:

  • Consistent key case throughout your code
  • Easy conversion of key case for compatibility with other systems or languages
  • Simplified code maintenance and debugging

Conclusion

In conclusion, the PHP Array Change Key Case function is a simple yet powerful tool for transforming the keys of an arrays from one case to another. Whether you need to convert the keys of an array to uppercase or lowercase, the Array Change Key Case function makes it easy to do so, offering several benefits including consistent key case throughout your code, easy conversion for compatibility with other systems or languages, and simplified code maintenance and debugging. So, next time you need to change the case of your array keys, consider using the Array Change Key Case function.

Источник

Оцените статью