user1542152
user1542152

Reputation:

array_search() for a value greater than or equal to a number?

I'm trying to figure out how I could search an array so that I can find a key in which has a value of greater than or equal to 1.

For instance:

array_search(>1, $array);

^ Illegal syntax

Upvotes: 1

Views: 5439

Answers (2)

kaiser
kaiser

Reputation: 22353

I'm using something pretty similar to build an array of week days:

// Set different value to test. 0 = Sunday, 1 = Monday
$start_of_week = 5;

// Build an array, where the values might exceed the value of 6
$days = range( $start_of_week, $start_of_week +6 );

// Check if we find a value greater than 6
// Then replace this and all following vals with an array of values lower than 6
if ( $found_key = array_search ( 7, $days ) )
    array_splice(
        $days,
        $found_key,
        7 -$found_key +1,
        range( 0, $days[ 0 ] -1 )
    );

// Check the days:
var_dump( $days );

Upvotes: 0

raidenace
raidenace

Reputation: 12836

array_search cannot have conditions as the needle to search for, instead use array_walk(). You can pass a custom function into array_walk and it will perform the function against each element of the array. Something like ..

array_walk($array, 'check_great_than_one_fn');

function check_great_than_one_fn($val)
{
  //if($val > 1) do whatever your heart pleases..
}

Read more about it at http://www.php.net/array_walk

Please note: the example I gave is very rudimentary and possibly even incorrect in terms of arguments and logic. It is only to give you an idea about how to go about it. Check the documentation in the link I gave to get a proper idea

Upvotes: 3

Related Questions