Change All Keys in an Array to Lowercase or Uppercase Without PHP Functions
Here’s how you can manually change the keys in an array to either lowercase or uppercase without using built-in PHP functions like array_change_key_case.
Example Code for Lowercase Keys
<!DOCTYPE html>
<html>
<body>
<?php
$array = [
"NAME" => "Dharmender Singh",
"EMAIL" => "dharmendersingh@blogshub.co.in",
"AGE" => 25
];
$lowercaseKeysArray = [];
foreach ($array as $key => $value) {
$newKey = '';
for ($i = 0; $i < strlen($key); $i++) {
$char = $key[$i];
// Convert to lowercase using ASCII values
if ($char >= 'A' && $char <= 'Z') {
$newKey .= chr(ord($char) + 32);
} else {
$newKey .= $char;
}
}
$lowercaseKeysArray[$newKey] = $value;
}
print_r($lowercaseKeysArray);
?>
</body>
</html>
Output:
Example Code for Uppercase Keys:
<!DOCTYPE html>
<html>
<body>
<?php
$array = [
"name" => "Dharmender Singh",
"email" => "dharmendersingh@blogshub.co.in",
"age" => 25
];
$uppercaseKeysArray = [];
foreach ($array as $key => $value) {
$newKey = '';
for ($i = 0; $i < strlen($key); $i++) {
$char = $key[$i];
// Convert to uppercase using ASCII values
if ($char >= 'a' && $char <= 'z') {
$newKey .= chr(ord($char) - 32);
} else {
$newKey .= $char;
}
}
$uppercaseKeysArray[$newKey] = $value;
}
print_r($uppercaseKeysArray);
?>
</body>
</html>
Output:
Explanation
- ASCII Manipulation:
- Lowercase letters range from ASCII 97 (a) to 122 (z).
- Uppercase letters range from ASCII 65 (A) to 90 (Z).
- To convert:
- Lowercase to uppercase: Subtract 32 from the ASCII value.
- Uppercase to lowercase: Add 32 to the ASCII value.
- Loop Through Keys: Iterate over the array and manually change each key using the ASCII values.
- Rebuild the Array: Store the updated keys in a new array while keeping the original values intact.
This approach is practical when you want to avoid using PHP’s built-in functions.
Keep Learning 🙂