0

how can i convert this array to string?

public static function generos($string) {
   return preg_replace(array("/(natacao)/"),explode(" ","Natação"), $string);
}

public function categoria($string) {
    $this->exp = explode(",", $string);
    foreach ($this->exp as $this->list) :
        return $this->generos(implode(",", $this->list));
    endforeach;
}

echo '<li>'.$this->categoria($rows[] = $this->row['categoria']).'</li>';

table

id  |  categoria  
 1  |  futebol, voleiball

Current results

<li>futebol, voleiball</li>

expected result

<li>futebol</li>
<li>voleiball</li>
9
  • 2
    implode("</li>\n<li>", $this->list) Commented Aug 12, 2019 at 17:20
  • Where is <li> and </li> coming from? I don't see it anywhere in the code. Commented Aug 12, 2019 at 18:11
  • Possible duplicate of Array to String PHP? Commented Aug 12, 2019 at 18:11
  • The return statement is ending the foreach loop during the first iteration. I don't see how you're getting both futebol and voleiball in the output. Commented Aug 12, 2019 at 18:12
  • It's generally not a good idea to store comma-separated lists in a database column. You should normalize your data. But that's a separate issue from this problem. Commented Aug 12, 2019 at 18:13

1 Answer 1

1

add your array's value to another variable like this:

<?php
    $dizi=array('mother','father','child'); //This is array

    $sayi=count($dizi);
    for ($i=0; $i<$sayi; $i++) {
        $dizin.=("'$dizi[$i]',"); //Now it is string...
    }
         echo substr($dizin,0,-1); //Write it like string :D
?>

In this code we added $dizi's values and comma to $dizin:

$dizin.=("'$dizi[$i]',");

Now

$dizin = 'mother', 'father', 'child',

It's a string, but it has an extra comma :)

And then we deleted the last comma, substr($dizin, 0, -1);

Output:

'mother','father','child'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.