PHP Laravel Convert array value to upper case
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
In your Laravel project, you've encountered a situation where you need to convert specific values within an array into upper case. In this comprehensive blog post, we will explore different methods and approaches you can follow using Laravel collections or other alternatives to achieve your goal efficiently.
1. Laravel Collection Magic: Laravel provides built-in Collection classes that enable easy manipulation of arrays. To perform the transformation on a given array, follow these steps: Example array:php
array:1434 [▼
0 => array:53 [▼
"contact" => "ANA (dependienta)"
"mail" => "example@mail.com"
"phone2" => ""
"phone3" => ""
"web" => "0"
"active" => true
"province" => "Zaragoza"
]
1 => array:53 [▼
"contact" => "JACKELINE * VIVIANA"
"mail" => "mail@example.com"
"phone2" => ""
"phone3" => ""
"web" => "0"
"active" => true
"province" => "Barcelona"
]php
$collection = collect($arrays); // Assuming $arrays is the array containing other data besides provinces
$collection->map(function ($value, $key) {
$province = $value['province'];
if (isset($province)) {
$newProvince = strtoupper($province);
return collect(['province' => $newProvince])->merge($value)->all();
} else {
return $value; // Return original values for keys not related to provinces
}
})->values()->all();php
$provinceValues = []; // Create an empty array to store the updated values
foreach ($arrays as $idx => $array) {
if (isset($array['province'])) {
$newProvince = strtoupper($array['province']);
$updatedArray[$idx] = ['province' => $newProvince]; // Update the array with new values
} else {
$updatedArray[$idx] = $array; // Keep original arrays for non-province keys
}
}php
foreach ($arrays as $idx => $array) {
if (isset($array['province'])) {
$newProvince = strtoupper($array['province']);
if (!empty($newProvince)) {
$updatedArray[$idx] = array_replace($array, [
'province' => $newProvince,
]);
} else {
$updatedArray[$idx] = $array;
}
} else {
$updatedArray[$idx] = $array; // Keep original arrays for non-province keys
}
}