0

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']  = '[email protected]';
$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 [email protected]

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

Is it somehow possible to get a string like ::[email protected] ::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.

1

6 Answers 6

3

There are two issues in your code:

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

How to achieve this result?

::[email protected] ::password

You can achieve this result by using this:

// example with your code
$array['a']  = '[email protected]';
$array['b'] = 'password';

echo "::".implode("::",$array);

Result:

::[email protected]::password

Some Optimization:

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

echo "::".implode("::",$_POST); //::[email protected]::password

Few Suggestion:

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

Error Reporting

Learn how implode() function works

PHP Implode()

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

Comments

1

You can use implode. It combines items of array with given parameter and returns a string. Here is the documentation of implode.

Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.

$array  = ['[email protected]', 'password'];
$string = implode(',', $array);
echo $string;

Comments

0

Try it this way

$array[]  = '[email protected]';
$array[] = 'password'
echo '::'.implode('::', $array);

output

::[email protected]::password

Comments

0

Try this:

echo ":: ".implode("::",$a);

Comments

0

Please try to use implode like this.

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

echo implode(',',$array);

Comments

0

Is it somehow possible to get a string like ::[email protected] ::passpword

Yes, prepend :: to each element, then implode with a single space.

Code: (Demo)

$array['a']  = '[email protected]';
$array['b'] = 'password';

echo implode(' ', substr_replace($array, '::', 0, 0));

Output:

::[email protected] ::password

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.