Question

alright, I'm trying something which should be like really easy.

Here it is:

usort($newarr, "cmp");

function cmp($a, $b)
{ return 0; }

The problem is simple: it does not sort the array by giving this warning message

Warning: usort() expects parameter 2 to be a valid callback, function 'cmp' not found or invalid function name

I have read this answer here PHP usort won't sort

but it just doesn't make any sense to me, I do not have a class like how it is explained in the answer 1 (and I don't even need any, i tried with $this, this, insted of "myclass" but it's simply not working any):

usort($items, array("MyClass", "compare_method"));
Was it helpful?

Solution

Change the script flow, by the time you are trying to sort your array cmp does not exists yet. So, this should work:

function cmp($a, $b)
{ return 0; }

usort($newarr, "cmp");

OTHER TIPS

From the information you've posted with your question, it can not be specifically said why it does not work for you.

The code generally does work, it's perfectly alright (Demo):

<?php
$newarr = array();

if (!function_exists('cmp')) echo "cmp() not defined yet.\n";
usort($newarr, "cmp");

function cmp($a, $b)
{ return 0; }

I suggest you add more information to your question so it can be better said where the actual problem is located.

  • Which PHP version are you using?
  • Do you make use of namespaces?

Use the anonymous functions (or create_function) to create an anonymous function like your cmp, then pass it to usort.

Example:

usort($newarr, function($a, $b) {
    return 0;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top