1

i have an array like this, with x-coordinate and y-coordinate forming an individual entry.

$polygon = array("10 0", "20 5", "15 15", "22 15");

Now how can i break this array into 2 different arrays, such that all x-coordinates will fall into one array and all y-coordinates will fall into another array, like this:

$x = array(10, 20, 15, 22);
$y = array(0, 5, 15, 15);

2 Answers 2

5
$x = $y = array();
$polygon = array("10 0", "20 5", "15 15", "22 15");
foreach ($polygon as $coor) {
    list($x[], $y[]) = explode(' ', $coor);
}

This will do the trick :)

And to combine them back:

//assuming that $x and $y have the same number of items
for ($i = 0; $i<count($x); $i++) {
    $polygon[] = $x[$i] .' ' . $y[$i];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Nice use of list() there, didn't know that was possible
Thanks for the answer, just curious to know, how to do the reverse of it? I mean, if i have the $x and $y arrays, how to generate $polygon array?
1

Try that:

$x = array();
$y = array();
foreach($polygon as $entry){
 $splitted = explode(" ", $entry);
 //append x and y 
 $x[] = $splitted[0];
 $y[] = $splitted[1];
}

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.