Reputation: 1611
I have this string in php.
$string = "17,3,25,29,35,81,40,45,50";
I need to explode it to an integer array and sort it in ascending order.
I used this code but that is not working.
$myArray = array_map('intval', explode(',', $string));
$sortedArray = sort($myArray);
print_r($sortedArray);
What is the error?
Upvotes: 1
Views: 1075
Reputation: 1485
$string = "17,3,25,29,35,81,40,45,50";
$array = array_filter(array_map('trim', explode(',', $string)));
asort($array);
$array = implode(', ', $array);
print_r($array);
Upvotes: 1
Reputation: 5625
sort
function doesn't return a sorted array, it sorts an argument array by reference. What you need to do is:
$myArray = array_map('intval', explode(',', $string));
sort($myArray);
print_r($myArray);
Upvotes: 4
Reputation: 487
<?php
$string = "17,3,25,29,35,81,40,45,50";
$myArray = explode(',', $string);
sort($myArray);
print_r($myArray);// to print array
echo $newstring =implode(',',$myArray);
Upvotes: 2