tags:

views:

55

answers:

2

Hi!

I'm trying to get all my first characters in a PHP array to be uppercase.

PHP code:

<?php
$ordlista = file_get_contents('C:/wamp/www/bilder/filmlista.txt');

$ord = explode("\n", $ordlista);

sort($ord,SORT_STRING);

foreach ($ord as $key => $val) {
    echo $val."<br/>";
}
?>

Thanks ahead for answers!

Solved:

<?php
$ordlista = file_get_contents('C:/wamp/www/bilder/filmlista.txt');

$ord = explode("\n", $ordlista);

$ord=array_map(function($word) { return ucwords($word); }, $ord);


sort($ord,SORT_STRING);

foreach ($ord as $key => $val) {
    echo $val."<br/>";
}
?>
+2  A: 
$ord=array_map(function($word) { return ucfirst($word); }, $ord);
icktoofay
Does'nt work...Notice: Use of undefined constant ucwords - assumed 'ucwords' in C:\wamp\www\sorting\sort.php on line 5Warning: array_map() expects parameter 1 to be a valid callback, array must have exactly two members in C:\wamp\www\sorting\sort.php on line 5Warning: sort() expects parameter 1 to be array, null given in C:\wamp\www\sorting\sort.php on line 7Warning: Invalid argument supplied for foreach() in C:\wamp\www\sorting\sort.php on line 9
Victor
@Victor: Try now. For some reason it doesn't like `ucwords` as a callback, and it has to be wrapped in a closure.
icktoofay
@icktoofay: Worked now, thanks!
Victor
@icktoofay That's not really a closure, that's an anonymous function. And functions in PHP are not first-class, so `array_map(ucfirst)` won't work, the correct syntax is `array_map('ucfirst')`.
deceze
@deceze: I was under the impression that it was a closure because if you run this in the PHP CLI interpreter: `<?php $hello=function() { echo "hello\n"; }; echo $hello; ?>`, you get an error saying `Object of class Closure could not be converted to string`. That, to me, says that it's a closure.
icktoofay
As the [manual states](http://www.php.net/manual/en/functions.anonymous.php): `Anonymous functions are currently implemented using the Closure class. This is an implementation detail.` It would be a closure if it *closed over* variables of the outer scope (using `use`), which it doesn't do. I guess the Closure class is used for any anonymous function because it's a subset of a closure. It's a fine distinction, admittedly. [Wikipedia even mentions](http://en.wikipedia.org/wiki/Closure_(computer_science%29): `The term closure is often mistakenly used to mean anonymous function.`
deceze
@deceze: I see. You're right, then. I wasn't aware of that.
icktoofay
+1  A: 
$ord = array_map('ucfirst', $ord);
iroel
or using anonymous function like this:<br/><code>$ord = array_map(create_function('$value', 'return ucfirst($value);'), $ord);</code>
iroel