Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort in explode variable [duplicate]

Tags:

php

sorting

Hello everyone I have a small problem with the php sort I have basically a variable example

$ciao  ="4,v@2,f@1,x@22,a"; // Can have other elements
$prova = explode("@",$ciao);
rsort($prova);
echo $prova[0];

but that's out 4,v Instead I would like so 1,x

like image 851
Davide Fish Avatar asked Mar 26 '26 13:03

Davide Fish


2 Answers

Use sort() simply.

<?php
$ciao  ="4,v@2,f@1,x@22,a"; // Can have other elements
$prova = explode("@",$ciao);
sort($prova);
echo $prova[0]; // Prints 1,x
?>

See it working live

like image 163
Pupil Avatar answered Mar 28 '26 02:03

Pupil


have a look at http://php.net/manual/en/function.sort.php, here you can use second parameter i.e. sort_flags

$ciao  ="4,v@2,f@1,x@22,a"; // Can have other elements
$prova = explode("@",$ciao);
sort($prova, SORT_STRING); //SORT_STRING - compare items as strings
print_r($prova);

sort($prova, SORT_NUMERIC); //SORT_NUMERIC - compare items numerically
print_r($prova);

output

Array
(
    [0] => 1,x
    [1] => 2,f
    [2] => 22,a
    [3] => 4,v
)
Array
(
    [0] => 1,x
    [1] => 2,f
    [2] => 4,v
    [3] => 22,a
)
like image 23
Chetan Ameta Avatar answered Mar 28 '26 02:03

Chetan Ameta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!