Friday, 19 September 2014

PHP: Split PHP Variable in to array

Source:ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234

Requirement:Split the above string into array

o/p:
$page_no=array([0] => 199,
[1] => 232,
[2] => 200,
[3] => 233,
[4] => 201,
[5] => 234);


Solution1:
<?php
    $str = "ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234";
    preg_match_all("/=([^&]+|.*$)/", $str, $matches);
    print_r($matches[1]);
?>


Solution2:

You can use parse_str to parse a query string. however it expects php's style of array syntax( key[]=val ) so you will need to add the square brackets:

  <?php

$str = 'ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234';
$str = str_replace('=','[]=',$str);
parse_str($str, $output);
$final = $output['ckb'];
//var_dump($final);
print_r($final);
?>


Solution3:

<?php

$string = 'ckb=199&ckb=232&ckb=200&ckb=233&ckb=201&ckb=234';
$pieces = array_map(function($piece){
    $sub_piece =  explode('=', $piece);
    return array_pop($sub_piece);
}, explode('&', $string));

echo '<pre>';
print_r($pieces);

?>

0 comments:

Post a Comment