bingjie2680
bingjie2680

Reputation: 7773

array_search wrong argument datatype

I am playing around with this:

$sort = array('t1','t2');

function test($e){
    echo array_search($e,$sort);
}

test('t1');

and get this error:

Warning: array_search(): Wrong datatype for second argument on line 4

if I call it without function like this, I got the result 0;

echo array_search('t1',$sort);

What goes wrong here?? thanks for help.

Upvotes: 0

Views: 1203

Answers (4)

sandip patil
sandip patil

Reputation: 658

take the $sort inside the function or pass $sort as parameter to function test()..

For e.g.

function test($e){
$sort = array('t1','t2');
    echo array_search($e,$sort);
}

test('t1');


----- OR -----
$sort = array('t1','t2');
function test($e,$sort){

    echo array_search($e,$sort);
}

test('t1',$sort);

Upvotes: 0

knittl
knittl

Reputation: 265251

You cannot directly access global variables from inside functions. You have three options:

function test($e) {
  global $sort;

  echo array_search($e, $sort);
}

function test($e) {
  echo array_search($e, $GLOBALS['sort']);
}

function test($e, $sort) {
  echo array_search($e, $sort);
} // call with test('t1', $sort);

Upvotes: 1

Amir
Amir

Reputation: 820

You must pass the array as a parameter! Because the functions variables are different from globals in php!

Here is the fixed one:

$sort = array('t1','t2');

function test($e,$sort){
    echo array_search($e,$sort);
}

test('t2',$sort);

Upvotes: 1

deceze
deceze

Reputation: 522135

Variables in PHP have function scope. The variable $sort is not available in your function test, because you have not passed it in. You'll have to pass it into the function as a parameter as well, or define it inside the function.

You can also use the global keyword, but it is really not recommended. Pass data explictly.

Upvotes: 4

Related Questions