Convert a number array to a single String in php

Asked

Viewed 856 times

0

as I transform an array of numbers into a single string in php?

In the code below the variable $result is the array of numbers, and I tried to convert it to a single string with the function implode(). But it doesn’t seem to work because php gives the message 'Notice: Array to string Conversion in..." (QUERY LINE

And in the database did not work persistence...

How to make this conversion?

//Result é o array de números. Preciso convertê-lo para uma String...
$resultado = implode($result);

        mysqli_query($con,"INSERT INTO forum (codUsuario,titulo,mensagem) VALUES('$result','$titulo','$mensagem');");
  • 1

    Failed to pass by which delimiter the string must be joined. $resultado = implode(',', $result);

  • Numbers must be concatenated without delimiters...

  • For example, if I have an array = [1, 2, 3]; I want a string "123"

  • Vc needs a delimiter, before saving in the bank can give str_replace to remove it

3 answers

1


In the implode function, I put the empty delimiter and it worked:

$resultado = implode('', $result);

1

The problem is you’re including the $result in the query and not the $resultado, you’re making:

$resultado = implode($result);

mysqli_query($con,"INSERT forum (...) VALUES('$result','$titulo','$mensagem');");
                                                 ^^^^

Just change to $resultado and will work normally. The implode, as documented, accepts to invert the parameters. This is both implode($array, '') how much implode('', $array) work, just like using the implode($array) in this case.

0

Other option - no delimiter required

Ideone

$meuArray = array( 1, 2, 3 );
$result="";
foreach( $meuArray  as  $valor ) {
    $result .= $valor;
}
echo $result; // 123

Sandbox

$meuArray =  [1, 2, 3];
$result="";
foreach( $meuArray  as  $valor ) {
    $result .= $valor;
}
echo $result; 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.