Reputation: 4207
How can I convert all values in an array to lowercase in PHP?
Something like array_change_key_case
?
Upvotes: 167
Views: 156341
Reputation: 47764
Native functions which effect the case of letters:
function | multibyte-safe | null-safe as of PHP8.1 |
---|---|---|
strtolower() |
❌️ | ❌️ |
strtoupper() |
❌️ | ❌️ |
ucfirst() |
❌️ | ❌️ |
lcfirst() |
❌️ | ❌️ |
ucwords() |
❌️ | ❌️ |
mb_strtolower() |
✅ | ❌️ |
mb_strtoupper() |
✅ | ❌️ |
mb_convert_case() |
✅ | ❌️ |
Most modern PHP frameworks offer string case altering and formatting functions/methods which have some relation to the above. Be sure to explore pre-existing formatting features as needed.
If the input array may possibly contain, it would be prudent to use a unicode-safe/multibyte-safe function. If the input array may contain non-string values, the implementation should check for a string datatype before executing the function on the value.
If processing an array guaranteed to contain ONLY strings, then you can modify each string by reference using a classic loop or array_walk()
array_walk($array, fn(&$v) => $v = strtolower($v));
// the callback's return value is not used, the $v assignment is necessary
// array_walk($array, 'strtolower'); cannot be used because:
// Fatal error: Uncaught ArgumentCountError: strtolower() expects exactly 1 argument, 2 given
Or
foreach ($array as &$v) {
$v = strtolower($v);
}
To return a new array, array_map()
will be most direct/concise. Below demonstrates the modern "First Class Callable" syntax of calling a function (no longer by a string-type name -- I personally dislike the syntax, but it is allegedly better supported by most IDEs).
var_export(
array_map(strtolower(...), $array)
);
If an array of arrays, recursion is not necessary; just nest one of the above techniques inside of another looping technique.
All previous guidance still applies. If processing an array which is guaranteed to ONLY represent levels as arrays, then array_walk_recursive()
is likely to be a suitable native method. Bear in mind that if any level contains an object, none of its children will be traversed by the native function.
array_walk_recursive(
$array,
fn(&$v) => $v = is_string($v) ? strtolower($v) : $v
);
Finally, if processing a data structure of unknown depth and with unknown data types, a custom recursive technique will be appropriate.
Modify by reference (adjust datatype allowances as needed) (Demo)
function recursiveWalker(array|object &$level, callable $callback) {
foreach ($level as &$v) {
switch (gettype($v)) {
case 'string':
$v = $callback($v);
break;
case 'array':
case 'object':
(__FUNCTION__)($v, $callback);
}
}
}
recursiveWalker($array, 'strtolower');
var_export($array);
Return new structure: (adjust datatype allowances as needed) (Demo)
function recursiveMapper(array|object &$level, callable $callback) {
$new = [];
foreach ($level as $k => $v) {
$new[$k] = match (gettype($v)) {
'string' => $callback($v),
'array', 'object' => (__FUNCTION__)($v, $callback),
default => $v
};
}
if (gettype($level) === 'object') {
$new = (object) $new;
}
return $new;
}
var_export(recursiveMapper($array, 'strtolower'));
This lengthy answer indicates that there is a fair bit of nuance and plenty of "gotchas" to avoid. Choosing the correct technique is largely dictated by the structure and quality of your data.
Upvotes: 0
Reputation: 3216
Target specific values with array_map
$myArray = $_POST['product_categories']
$lowercaseArray = array_map(function ($value){
if(isset($value['title'])) {
$value['title'] = trim(strtolower($value['title']));
}
return $value;
}, $myArray);
Upvotes: 0
Reputation: 113
$Color = array('A' => 'Blue', 'B' => 'Green', 'c' => 'Red');
$strtolower = array_map('strtolower', $Color);
$strtoupper = array_map('strtoupper', $Color);
print_r($strtolower);
print_r($strtoupper);`
Upvotes: 9
Reputation: 57
Hi, try this solution. Simple use php array map
function myfunction($value)
{
return strtolower($value);
}
$new_array = ["Value1","Value2","Value3" ];
print_r(array_map("myfunction",$new_array ));
Output Array ( [0] => value1 [1] => value2 [2] => value3 )
Upvotes: 0
Reputation: 21979
use array_map()
:
$yourArray = array_map('strtolower', $yourArray);
In case you need to lowercase nested array (by Yahya Uddin):
$yourArray = array_map('nestedLowercase', $yourArray);
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
Upvotes: 439
Reputation: 563
AIO Solution / Recursive / Unicode|UTF-8|Multibyte supported!
/**
* Change array values case recursively (supports utf8/multibyte)
* @param array $array The array
* @param int $case Case to transform (\CASE_LOWER | \CASE_UPPER)
* @return array Final array
*/
function changeValuesCase ( array $array, $case = \CASE_LOWER ) : array {
if ( !\is_array ($array) ) {
return [];
}
/** @var integer $theCase */
$theCase = ($case === \CASE_LOWER)
? \MB_CASE_LOWER
: \MB_CASE_UPPER;
foreach ( $array as $key => $value ) {
$array[$key] = \is_array ($value)
? changeValuesCase ($value, $case)
: \mb_convert_case($array[$key], $theCase, 'UTF-8');
}
return $array;
}
Example:
$food = [
'meat' => ['chicken', 'fish'],
'vegetables' => [
'leafy' => ['collard greens', 'kale', 'chard', 'spinach', 'lettuce'],
'root' => ['radish', 'turnip', 'potato', 'beet'],
'other' => ['brocolli', 'green beans', 'corn', 'tomatoes'],
],
'grains' => ['wheat', 'rice', 'oats'],
];
$newArray = changeValuesCase ($food, \CASE_UPPER);
Output
[
'meat' => [
0 => 'CHICKEN'
1 => 'FISH'
]
'vegetables' => [
'leafy' => [
0 => 'COLLARD GREENS'
1 => 'KALE'
2 => 'CHARD'
3 => 'SPINACH'
4 => 'LETTUCE'
]
'root' => [
0 => 'RADISH'
1 => 'TURNIP'
2 => 'POTATO'
3 => 'BEET'
]
'other' => [
0 => 'BROCOLLI'
1 => 'GREEN BEANS'
2 => 'CORN'
3 => 'TOMATOES'
]
]
'grains' => [
0 => 'WHEAT'
1 => 'RICE'
2 => 'OATS'
]
]
Upvotes: 1
Reputation: 28841
If you wish to lowercase all values in an nested array, use the following code:
function nestedLowercase($value) {
if (is_array($value)) {
return array_map('nestedLowercase', $value);
}
return strtolower($value);
}
So:
[ 'A', 'B', ['C-1', 'C-2'], 'D']
would return:
[ 'a', 'b', ['c-1', 'c-2'], 'd']
Upvotes: 5
Reputation: 31
array_change_value_case
by continue
function array_change_value_case($array, $case = CASE_LOWER){
if ( ! is_array($array)) return false;
foreach ($array as $key => &$value){
if (is_array($value))
call_user_func_array(__function__, array (&$value, $case ) ) ;
else
$array[$key] = ($case == CASE_UPPER )
? strtoupper($array[$key])
: strtolower($array[$key]);
}
return $array;
}
$arrays = array ( 1 => 'ONE', 2=> 'TWO', 3 => 'THREE',
'FOUR' => array ('a' => 'Ahmed', 'b' => 'basem',
'c' => 'Continue'),
5=> 'FIVE',
array('AbCdeF'));
$change_case = array_change_value_case($arrays, CASE_UPPER);
echo "<pre>";
print_r($change_case);
Array ( [1] => one [2] => two [3] => three [FOUR] => Array ( [a] => ahmed [b] => basem [c] => continue ) [5] => five [6] => Array ( [0] => abcdef ) )
Upvotes: 3
Reputation: 697
You can also use a combination of array_flip()
and array_change_key_case()
. See this post
Upvotes: -3
Reputation: 906
array_map()
is the correct method. But, if you want to convert specific array values or all array values to lowercase one by one, you can use strtolower()
.
for($i=0; $i < count($array1); $i++) {
$array1[$i] = strtolower($array1[$i]);
}
Upvotes: 2
Reputation: 27525
Just for completeness: you may also use array_walk
:
array_walk($yourArray, function(&$value)
{
$value = strtolower($value);
});
From PHP docs:
If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.
Or directly via foreach
loop using references:
foreach($yourArray as &$value)
$value = strtolower($value);
Note that these two methods change the array "in place", whereas array_map
creates and returns a copy of the array, which may not be desirable in case of very large arrays.
Upvotes: 34
Reputation: 5110
You could use array_map(), set the first parameter to 'strtolower' (including the quotes) and the second parameter to $lower_case_array.
Upvotes: 8