views:

60

answers:

2

hi, i got problem with my code and hopefully someone able to figure it out. The main purpose is to sort array based on its value (then reindex its numerical key).

i got this sample of filename :

  $filename = array("index 198.php", "index 192.php", "index 144.php", "index 2.php",  "index 1.php", "index 100.php", "index 111.php");

  $alloutput = array(); //all of index in array

  foreach ($filename as $name) {
    preg_match('#(\d+)#', $name, $output);      // take only the numerical from file name 
    array_shift($output);                       // cleaned. the last code create duplicate numerical in $output, 
    if (is_array($output)) {
        $alloutput = array_merge($alloutput, $output);
    }
  }


//try to check the type of every value in array
foreach ($alloutput as $output) { 
    if (is_array($output)) {
        echo "array true </br>";        
    } elseif (is_int($output)) {
        echo "integer true </br>";
    } elseif (is_string($output)) {   //the numerical taken from filename always resuld "string". 
        echo "string true </br>";
    }   
}

the output of this code will be :

Array ( [0] => 198 [1] => 192 [2] => 144 [3] => 2 [4] => 1 [5] => 100 [6] => 111 )

i have test every output in array. It's all string (and not numerical), So the question is how to change this string to integer, so i can sort it from the lowest into the highest number ?

the main purpose of this code is how to output array where it had been sort from lowest to highest ?

A: 

Use intval

$number_string = '14';
$number = intval('14');

With intval you can specify also the basis. If the number is decimal, hower, you can also use

$number = (int) $number_string;
Nicolò Martini
i know about this. but i hope the solution given in the first foreach. so it will be more directly.sorry if it's too much
justjoe
+1  A: 

preg_match will keep the matched part in $outpu[1], so you can make use of that to convert the string to int and then add it to your alloutput array.

foreach ($filename as $name) {
    preg_match('#(\d+)#', $name, $output);
    $alloutput[] = intval($output[1]);
}
codaddict
it's you again...lol Thanks i will try to find the way to sort it ;D
justjoe
sorry i use the wrong code in the above code. but i understand your answer ;D
justjoe
@justjoe: To sort you can use the sort function. Also you need not have to convert the strings to int before you sort. The sort function takes an argument SORT_NUMERIC. Which will treat your array elements are numeric. Give it a try.
codaddict
wow, this solution make the code more shorter and compact
justjoe