Nick
Nick

Reputation: 906

sort() returns true instead of the sorted array

Odd...

// array sort test

$_ar = array(
  0 => "2015-02-23",
  1 => "2015-02-21",
  2 => "2015-02-28",
  3 => "2015-03-20",
  4 => "2015-03-14",
  5 => "2015-03-21",
  6 => "2015-02-21",
  7 => "2015-02-28",
  8 => "2015-03-07",
  9 => "2015-03-14",
);
$_ar = sort($_ar);

var_dump($_ar);
// returns bool(true)

$__ar = array(
  0 => "2015 02 23",
  1 => "2015 02 21",
  2 => "2015 02 28",
  3 => "2015 03 20",
  4 => "2015 03 14",
  5 => "2015 03 21",
  6 => "2015 02 21",
  7 => "2015 02 28",
  8 => "2015 03 07",
  9 => "2015 03 14",
);
$__ar = sort($__ar);

var_dump($__ar);
// returns bool(true)

$ar = array(
  0 => "20150223",
  1 => "20150221",
  2 => "20150228",
  3 => "20150320",
  4 => "20150314",
  5 => "20150321",
  6 => "20150221",
  7 => "20150228",
  8 => "20150307",
  9 => "20150314",
);

$ar = sort($ar);

var_dump($ar);
// returns bool(true)

I am expecting this to return the array sorted by the date value. I thought maybe it was the - (hyphen) or spaces, but in all my examples my PHP var_dump simply returns bool(true) for each instance. Can someone confirm they get the same, or point out what I must be missing.... I have tried asort() - still the same.

Upvotes: 0

Views: 87

Answers (2)

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

The sort and asort function returns bool value. Just call this function and it will sort the array, don't store it , it returns true or false.Use the code below

// array sort test

$_ar = array(
  0 => "2015-02-23",
  1 => "2015-02-21",
  2 => "2015-02-28",
  3 => "2015-03-20",
  4 => "2015-03-14",
  5 => "2015-03-21",
  6 => "2015-02-21",
  7 => "2015-02-28",
  8 => "2015-03-07",
  9 => "2015-03-14",
);
 sort($_ar);

var_dump($_ar);
// returns bool(true)

$__ar = array(
  0 => "2015 02 23",
  1 => "2015 02 21",
  2 => "2015 02 28",
  3 => "2015 03 20",
  4 => "2015 03 14",
  5 => "2015 03 21",
  6 => "2015 02 21",
  7 => "2015 02 28",
  8 => "2015 03 07",
  9 => "2015 03 14",
);
$__ar = sort($__ar);

var_dump($__ar);
// returns bool(true)

$ar = array(
  0 => "20150223",
  1 => "20150221",
  2 => "20150228",
  3 => "20150320",
  4 => "20150314",
  5 => "20150321",
  6 => "20150221",
  7 => "20150228",
  8 => "20150307",
  9 => "20150314",
);

sort($ar);

var_dump($ar);
// returns bool(true)

Hope this helps you

Upvotes: 1

Rizier123
Rizier123

Reputation: 59691

You don't have to assign the return value of sort(). For more information about sort() see the manual: http://php.net/manual/en/function.sort.php

And a quote from there:

Returns TRUE on success or FALSE on failure.

So just to this:

sort($_ar);

Side Note:

I wouldn't recommend you to define variables with underscores at the start of the name, since this already get's used by defined php variables e.g. super globals or magic constants

Upvotes: 2

Related Questions