Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ucwords function issue

Tags:

function

php

I need to make a function that reads my variables at the top and fixes the string so that each word in it has a capital letter. The way I'm currently doing it doesn't seem to work. Here is what I have:

<?php
$course1 = "advanced web development";
$course2 = "mobile app development";
$course3 = "info systems with business intell";
function fixCourseName($courseName) {
    $courseName = ucwords($courseName);
}

fixCourseName($course1);
echo $course1;
?>

Does anyone know what would be causing the output to still be lower case?

like image 232
yes indeed Avatar asked Mar 04 '26 22:03

yes indeed


1 Answers

You can either pass it by reference, by using the & operator in front of the variable when passing it as an argument. This will change the variable you pass through, without having to return it. The variable is then changed in the global scope.

function fixCourseName(&$courseName) {
    $courseName = ucwords($courseName);
}
fixCourseName($course1);
echo $course1;
  • PHP docs: Passing by Reference

You can also return the new value, but then it must be assigned again.

function fixCourseName($courseName) {
    return ucwords($courseName);
}
$course1 = fixCourseName($course1);
echo $course1;

The better solution, if the fixCourseName() function does nothing more than using ucwords(), you might as well just use

$course1 = ucwords($course1);
echo $course1;

See this live demo to see it all in action.

like image 196
Qirel Avatar answered Mar 08 '26 08:03

Qirel