phparraysprefiximplode

Add prefix to array elements then join into a string


I have an array like the one below, which actually collects login and other data from a user submitted form, to be written to a DB. I don't need all the form data, and hence this approach.

$array['a']  = $_POST['userName'];
$array['a'] .= $_POST['passWord'];

Which results in:

$array['a']  = 'username@example.com';
$array['a'] .= 'password';

I'm trying to get values from the array as a string, sperated by , or ::, but just cannot figure how to do it.

Using implode gives me a continious string like username@example.compassword

$comma_separated = implode($array); echo $comma_separated;

Is it somehow possible to get a string like ::username@example.com ::passpword from the array without a for loop.

The approach cannot be changed since it's already in a working site.

I'm using PHP 7.0 on a Windows 10 Machine for testing.


Solution

  • There are two issues in your code:

    1. wrong implementation of implode();
    2. Same array index

    How to achieve this result?

    ::username@example.com ::password
    

    You can achieve this result by using this:

    // example with your code
    $array['a']  = 'username@example.com';
    $array['b'] = 'password';
    
    echo "::".implode("::",$array);
    

    Result:

    ::username@example.com::password
    

    Some Optimization:

    As you mentioned you are using form with POST method than you can use like that:

    echo "::".implode("::",$_POST); //::username@example.com::password
    

    Few Suggestion:

    Add error_reporting at the top of the file for getting errors.

    Error Reporting

    Learn how implode() function works

    PHP Implode()