0

I have an application (iOS) written in swift that makes an http post request to a PHP script. I want to pass an array from swift to the PHP API. Swift arrays are formatted as follows:

var array = [1, 2, 3, 4, 5]

and PHP arrays are obviously formatted like this:

$array = array(1, 2, 3, 4, 5);

However, when I try to call

$_POST['arrayFromSwift'];

I can't access indexes of individual items. How can I parse the array (either in swift or in the PHP API so that I can access individual items?

Thanks!

2
  • 1
    What's the value of $_POST['arrayFromSwift']? Do a var_dump($_POST['arrayFromSwift']);. Commented Apr 21, 2015 at 21:46
  • 1
    If you Stringify that array you should be able to make something out of it with json_decode() in PHP. Commented Apr 21, 2015 at 21:50

1 Answer 1

3

If your values are coming into the php page like this:

[1,2,3,4,5]

Then you could use php's explode function

array explode ( string $delimiter , string $string [, int $limit ] )

like this:

$val = $_POST['arrayFromSwift']);
// Cut off the end brackets and separate by comma
$array = explode(",", substr($val, 1, -1));

EDIT:

The reason you have to manually parse it is because PHP receives the POST data as a raw string which you must manually convert to a PHP array in order to use it in PHP as an array object.

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

5 Comments

It should still be passed as an array rather than a string(hopefully at least).
@ViperCode PHP Receives the data as a string coming from the raw socket, you have to interpret the value as an array yourself. (just like parsing json requests)
Ah gotcha! Should add that to your answer for future reference. Completely skipped my mind.
This works! thanks! Would this still work if the swift array included quotes around the items?
It depends on what you mean by 'work', it would do the samething only each value in the array would contain the quotes as well. You would have to run a str_replace() on the string first to remove the quotes like so str_replace('"', "", $val); str_replace("'", "", $val); But to warn you, that will remove every quote in the string, so if you had the string: "I haven't seen it" then the single quote in haven't would also be removed, so it's all how you choose to format it

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.