PHP:数组值到字符串

So I’m trying to convert each value, of an array, into a string.. But I can’t get it to work. My best result is to get letters from the values.

I have a form where I post checkbox values into the database and later I want to echo the selected values:

<form method="POST">
<div class="form-group">
   <label class="form-check-inline">
      <input class="form-check-input" type="checkbox" name="genre[]" value="Rock"> Rock</label>

<label class="form-check-inline">
   <input class="form-check-input" type="checkbox" name="genre[]" value="Funk"> Funk</label>

<label class="form-check-inline">
   <input class="form-check-input" type="checkbox" name="genre[]" value=“Jazz”> Jazz</label>
</div>
</form>

if(isset($_POST['update_profile'])){
    $genre = implode(',', $_POST['genre']);
    $sql_update = "UPDATE user_profile SET genre = ‘$genre’ WHERE user_id = ‘$user_id’”;
…
}

In the database row the selected value look like this; “Rock, Funk, Jazz”

Fine. Everything seems to work as it should. But I can’t figure out how to separate the values..

        if($result = mysqli_query($con, $sql_all_users)){
          if(mysqli_num_rows($result) > 0){
            while ($row = mysqli_fetch_row($result)){
              $row_genre = array($row[1]);

        foreach ($row_genre as $key => $value) {
        echo $value[1];
        }

        }
    }
}

When I do a print_r ($row_genre); I get this result:

Array ( [0] => Rock,Funk,Jazz)

What kind of a array is that?

The result I echo in the foreach is R (The first letter in Rock - The first value ) I have tried to implode.. Dosen’t make a difference. So how can I convert each value to a string?

Looks like like $row[1] = Rock,Funk,Jazz so $row[1] itself is a string and comma-separated values.

If you want to convert the string to an array you can do it using explode function:

$row_genre = explode(',', $row[1]);

You can then go through that $row_gen array like this:

foreach($row_genre as $val) {
    echo $val;
}

You have an array that contains one element that is a string. You can get the array value as its string by $row_genre[0]. Or if you would prefer, you can perform an explode(..) on $row_genre[0] to split the comma separated values into their own array.

$genres = explode(',', $row_genre[0]);

http://php.net/manual/en/function.explode.php