S
S
Schoolboy.2015-09-27 12:25:35
PHP
Schoolboy., 2015-09-27 12:25:35

How to compare a variable with an array?

How to compare variable with array in php?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Optimus, 2015-09-27
@viphorizon

in loop compare variable with each value in array

M
Maxim E, 2015-09-27
@creativeworm

You can use in_array() or array_search()

in_array -- Check if value is present in array
Description
bool in_array ( mixed needle, array haystack [, bool strict] ) Looks up needle
in haystack and returns TRUE on success, FALSE otherwise.
If the third parameter strict is set to TRUE then the in_array() function will also check whether the types parameter of needle matches the corresponding value of the haystack array.
Note: If needle is a string, the comparison will be case sensitive.
Note: In PHP versions prior to 4.2.0, the needle parameter cannot be an array.

Usage example:
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}
if (in_array("mac", $os)) {
    echo "Got mac";
}
?>

Source: PHP.SU
array_search -- Searches an array for a given value and returns the corresponding key if successful
Description
mixed array_search ( mixed needle, array haystack [, bool strict] )
Searches the haystack for needle and returns the key if it exists in the array, FALSE otherwise .
Note: If needle is a string, the comparison is case-sensitive.
Note: Prior to PHP 4.2.0, array_search() returned NULL instead of FALSE on failure.
If you pass TRUE as the optional third parameter of strict, the array_search() function will also check the type of needle in the haystack array.
If needle is present more than once in the haystack, the first key found will be returned. To return the keys for all found values, use the array_keys() function with the optional search_value parameter.

Example:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 0x000000, 3 => 'green', 4 => 'red');

$key = array_search('red', $array);         // $key = 1;
$key = array_search('green', $array);       // $key = 2; (0x000000 == 0 == 'green')
$key = array_search('green', $array, true); // $key = 3;
?>

Source: PHP.SU

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question