-2

My code:

function sortx($a, $b) {
    if(!strpos($a["p_title"],'apple ipad')) {
        return -1; 
    }
    return 1;
}
usort($arr, 'sortx');`

In above function I want to pass: $sort_text='apple ipad'; , when calling function instead of hardcoding apple ipad into strpos(). How can I accomplish that?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Ahmed Syed
  • 1,179
  • 2
  • 18
  • 44
  • Note: you are paobably using `!strpos(...)` incorrectly. This evaluates to true if string does not contain "apple ipad" or begins with "apple ipad" – Salman A Apr 23 '15 at 12:30
  • possible duplicate of [Pass extra parameters to usort callback](http://stackoverflow.com/questions/8230538/pass-extra-parameters-to-usort-callback) – Kevin Brown-Silva Apr 23 '15 at 12:45
  • @Rizier123, this is not duplicate, because here I want to pass whole function inside usort() function, please remove it from duplicate category. – Ahmed Syed Apr 26 '15 at 07:30
  • @MujahedAKAS Where did I say that this is a dupe? – Rizier123 Apr 26 '15 at 07:36
  • sorry Rizier123 it was @kewin Brown, Salman A, I will use `strpos($a["p_title"],'apple ipad') !== false` – Ahmed Syed Apr 26 '15 at 07:40

1 Answers1

3

Call it with a closure:

$sort_text='apple ipad';
usort(
    $arr, 
    function ($a, $b) use ($sort_text) {
        if(!strpos($a["p_title"], $sort_text)) {
            return -1; 
        }
        return 1;
    }
);

and you can pass additional arguments with the use clause

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • 1
    My bad.... remove the function name.... it's using an anonymous function, so it doesn't have a name... that'll teach me to cut/paste from the question.... answer edited accordingly – Mark Baker Apr 23 '15 at 12:21