1

I have a string having 128 values in the form of :

1,4,5,6,0,0,1,0,0,5,6,...1,2,3.

I want to pair in the form of :

(1,4),(5,6),(7,8)

so that I can make a for loop for 64 data using PHP.

1
  • explode on coma. foreach() loop and build Commented Apr 16, 2013 at 4:20

2 Answers 2

3

You can accomplish this in these steps:

  1. Use explode() to turn the string into an array of numbers

  2. Use array_chunk() to form groups of two

  3. Use array_map() to turn each group into a string with brackets

  4. Use join() to glue everything back together.

You can use this delicious one-liner, because everyone loves those:

echo join(',', array_map(function($chunk) {
    return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));

Demo

If the last chunk is smaller than two items, it will use '0' as the second value.

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

7 Comments

for odd values we would receive : (1,2),(3,4), and the last value gets removed. In my code,I am making loop using for and concatenating with comma.
@TusharKanti you mentioned there are 128 values, that's not an odd number.
ok my fault for it.sorry but That I just gave it as an example.The function should should work irrespective of how many values is there in the string and return in pair format.
Also,I am getting this Warning error on Wamp Client server : Warning: vsprintf(): Too few arguments in C:\wamp\www\test\explode\test.php on line 12
@TusharKanti so the last item should be ignored if the list has an odd number of items?
|
1
<?php
$a = 'val1,val2,val3,val4';

function x($value)
    {
        $buffer = explode(',', $value);
        $result = array();

        while(count($buffer))
            { $result[] = array(array_shift($buffer), array_shift($buffer)); }

        return $result;
    }

$result = x($a);

var_dump($result);
?>

Shows:

array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }

If modify it, then it might help you this way:

<?php
$a = '1,2,3,4';

function x($value)
    {
        $buffer = explode(',', $value);
        $result = array();

        while(count($buffer))
            { $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }

        return implode(',', $result);
    }

$result = x($a);

var_dump($result);
?>

Which shows:

string(11) "(1,2),(3,4)"

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.