Open In App

PHP Change strings in an array to uppercase

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

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:

  • use array_flip() function swap keys with the values present in the array. That is, the keys will now become values and their respective values will be their new keys.
  • use array_change_key_case() function to change case of current keys(original values).
  • use array_flip() function again to flip key and values of array to obtain original array where strings value are in upper case.

Below is the implementation of above approach in PHP: 


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.


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:


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

Next Article

Similar Reads