PHP Change strings in an array to uppercase (original) (raw)

Last Updated : 17 Jul, 2024

**Changing strings in an array to uppercase means converting all the string elements within the array to their uppercase equivalents. This transformation modifies the array so that every string, regardless of its original case, becomes fully capitalized.

**Examples:

Input : arr[] = ("geeks", "For", "GEEks")
Output : Array ([0]=>GEEKS [1]=>FOR [2]=>GEEKS)

Input : arr[] = ("geeks")
Output : Array ([0]=>GEEKS)

Here we have some common approaches:

Table of Content

Using array_change_key_case() and array_flip().

What we have to do is just flip the array keys to value and vice-versa after that change the case of new keys of array which actually changes the case of original strings value and then again flip the key and values by array_flip(). Below is the step by step process:

Below is the implementation of above approach in PHP:

PHP `

value input=arrayflip(input = array_flip(input=arrayflip(input); // Step 2: change case of new keys to upper input=arraychangekeycase(input = array_change_key_case(input=arraychangekeycase(input, CASE_UPPER); // Step 3: reverse the flip process to // regain strings as value input=arrayflip(input = array_flip(input=arrayflip(input); // print array after conversion of string print"\nArray after string conversion:\n"; print_r($input); ?>

`

Output

Array before string conversion: Array ( [0] => Practice [1] => ON [2] => GeeKs [3] => is best )

Array after string conversion: Array ( [0] => PRACTICE [1] => ON [2] => GEE...

Using strtoupper method

The PHP code iterates through each element in an array. If an element is a string, it converts it to uppercase using strtoupper() and updates the array. Non-string elements are unchanged.

**Example: In this example the changeStringsToUpperCase function converts string elements in an array to uppercase. It iterates through the array, checks each value for a string type, and applies strtoupper.

PHP `

key=>key => key=>value) { // Check if $value is a string if (is_string($value)) { // Convert $value to uppercase array[array[array[key] = strtoupper($value); } } return $array; } $array = ["apple", "banana", "Cherry", 123, "date"]; // Change strings to uppercase upperArray=changeStringsToUpperCase(upperArray = changeStringsToUpperCase(upperArray=changeStringsToUpperCase(array); // Print the modified array print_r($upperArray); ?>

`

Output

Array ( [0] => APPLE [1] => BANANA [2] => CHERRY [3] => 123 [4] => DATE )

Using array_map()

The array_map() function applies a callback to each element of an array. In this case, we'll use the strtoupper() function as the callback to convert each string in the array to uppercase.

**Example:

PHP `

upperArray=changeStringsToUpperCase(upperArray = changeStringsToUpperCase(upperArray=changeStringsToUpperCase(array); print_r($upperArray); ?>

`

Output

Array ( [0] => APPLE [1] => BANANA [2] => CHERRY [3] => 123 [4] => DATE )