1

I have this array ($recip):

Array
(
    [0] => 393451234567
    [1] => 393479876543
)

SMS API provider requires numbers in this format:

recipients[]=393334455666&recipients[]=393334455667

With

$recipients = implode('&recipients[]=',$recip);

I can obtain only this:

393471234567&recipients[]=393459876543

This output is missing the first key declaration.

5 Answers 5

2

Just append the initial recipients[]= to the front of your string:

$recipients = 'recipients[]=' . implode('&recipients[]=',$recip);
Sign up to request clarification or add additional context in comments.

1 Comment

The drawback of this approach is that, if the array is empty, the output will incorrectly be recipients[]=.
1

Your requested string will work as a querystring, but it is not a url-encoded querystring. I'll demonstrate solutions for both variations. Demo

For a fully url-encoded string which is effectively identical to your desited result, use native PHP function http_build_query(). This will encode the square braces and explicitly declare the indexes for each element of the array.

$array = ['393451234567', '393479876543'];

echo http_build_query(['recipients' => $array]);
recipients%5B0%5D=393451234567&recipients%5B1%5D=393479876543

Alternatively, achieve your desired result by prepending the key assignment string to each array value, then implode with &.

echo implode('&', substr_replace($array, 'recipients[]=', 0, 0));
recipients[]=393451234567&recipients[]=393479876543

Both snippets above will correctly return an empty string if given an empty array.

Comments

0

Another option:

foreach ($array as $key => $value){
    $array[$key] = (($key == 0) ? '' : '&').'recipients[]='.$value;
}
$result = implode('',$array);

A foreach loop allows you to conctenate your string. I include a check to avoid appending the & on the first part of the string.

Pointing this out as an option, but the other way is simpler!

Comments

0

Try this:

vsprintf('recipients[]=%s&recipients[]=%s', $recip);

Comments

0

Another option

foreach ($recip as $ip){
    $array[] = 'recipients[]=' . $ip;
}
$result = implode('&',$array);

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.