将数组转换为字符串

I am doing an assignment on how to take a string of text separated by commas and reverse the individual words and return the words in the same order.

This code does that but it is not returning it as a string for some reason and i do not understand.

<?php
function bassAckwards($input)
{
    // YOUR CODE HERE

    $commas = substr_count($input, ",");
    $NumWords = ($commas + 1);
    $words = array($input);
    for($x=0;$x<$NumWords;$x++)
    {
        $answer = array(strrev($words[$x]));
        $answer = implode(",",$answer);
        print $answer;
    }
}  
?>
$reversedWords = array();

// Explode by commas
$words = explode(',', $input);
foreach ($word in $words) {
    // For each word
    // Stack it, reversed, in the new array $reversedWords
    $reversedWords[] = strrev($word);
}

// Implode by commas
$output = implode(',', $reversedWords);

print $output;
function bassAckwards($str){
  $words = explode(',', $str);
  $reversedWords = array_map('strrev', $words);
  return implode(',', $reversedWords);
}

var_dump(bassAckwards('foo,bar,baz')); // string(11) "oof,rab,zab"

Save yourself some headaches and use the built-it functions.

  • explode
    make 'foo,bar,baz' => array('foo','bar','baz')
  • array_map & strrev
    Execute strrev (string reverse) on every element of the array with array_map and return the [modified] array back.
  • implode
    convert the array back to a csv.