Xfact Xfact - 6 months ago 5x
PHP Question

Sorting an array by a key - PHP

I have a program that allows users to add an proposal to a review board. I passed in a firstname and a proposal message from a form, stored it into a string, and stored it into an indexed array. I'm very new to PHP.

Example of the string:

$text = "UserName:$user<br/>Proposal:$prop";

When displayed it looks like:

UserName: " "

Proposal: " "

UserName: " "

Proposal: " "

I'd like to give the user the option to sort alphabetically by username:

The array looks like:

0 => UserName:bfoo<br/>Proposal:foo foo
1 => UserName:afoo<br/>Proposal:foo foo
2 => UserName:cfoo<br/>Proposal:foo foo)

After sorting by username I want it to look like:

0 => UserName:afoo<br/>Proposal:foo foo
1 => UserName:bfoo<br/>Proposal:foo foo
2 => UserName:cfoo<br/>Proposal:foo foo)


I think you are looking for something like this:

usort($array, function($a, $b) {

$lines_a = explode("<br/>", $a);
$lines_b = explode("<br/>", $b);

return strcmp(str_replace("UserName:", "", $lines_a[0]), str_replace("UserName:", "", $lines_b[0]));

However, if you sort by the values, it is going to give you the correct result as well (Because the UserName: string is identical in all the values and we don't really care what's after the names.

So just use this: sort .