I am trying to form an acronym from a given text. The Idea here is that the first Letter in $text ($text[0]) will be taken and placed inside the array $storage using array_push(). Now, if there is a space inside the array, the letter of the next index should be a part of the Acronym. I am currently not getting an ouput, what am I missing?
public function Acronym($text)
{
$text = str_split($text);
$count = strlen($text);
$storage = array();
for($i=0; $i<$count; $i++)
{
array_push($storage, $text[0]);
if($text[$i]==' ')
{
array_push($storage, $text[$i+1]);
}
foreach($storage as $clean)
{
echo $clean;
}
}
}
Your algorithm suffers from a few fatal flaws:
You’re calling
strlen()on an array, when you should be callingcount():However, you can index strings as arrays, so you don’t need
str_split()in this scenario, and you can keep$count = strlen( $text);by removing the call tostr_split().This should only happen once, so it should be outside the loop (This implies starting
$iat 1):Your
foreachloop that prints the$storagearray should be outside of the loop that is creating the acronym.You can save the overhead of calling a function by using the shorthand
array_push()notation. You should usearray_push()when adding more than one element to an array. Otherwise, this will suffice:You need to
returnsomething from your function, otherwise you won’t be able to access anything outside of it.Put that all together, and you get this:
That being said, there are far better implementations for forming an acronym giving a string input. Here is one that I can think of:
Note that both functions will fail for inputs like
Hello World. I am leaving it up to the OP to make these modifications (if necessary).