Home > Article > Backend Development > How to determine whether a character is in an array in php
In PHP, there are many methods to determine whether a character is in an array.
1. Use the in_array() function
The in_array() function can be used to determine whether a value is in an array, and the return value is true or false.
Sample code:
$array = array('apple', 'banana', 'orange'); if (in_array('apple', $array)) { echo 'yes'; } else { echo 'no'; }
The output result is: yes
2. Use array_search() function
array_search() function can be used to find a value The position in the array, or false if it does not exist.
Sample code:
$array = array('apple', 'banana', 'orange'); $key = array_search('banana', $array); if ($key !== false) { echo 'yes'; } else { echo 'no'; }
The output result is: yes
3. Use the in_array() function and strict parameters
The third of the in_array() function One parameter can specify whether case sensitivity is required. If case sensitivity is required, specify true.
Sample code:
$array = array('apple', 'banana', 'orange'); if (in_array('Apple', $array, true)) { echo 'yes'; } else { echo 'no'; }
The output result is: no
4. Use the array_search() function and strict parameters
The third of the array_search() function Each parameter can also specify whether it is case-sensitive.
Sample code:
$array = array('apple', 'banana', 'orange'); $key = array_search('Apple', $array, true); if ($key !== false) { echo 'yes'; } else { echo 'no'; }
The output result is: no
5. Use the in_array() function and array_map() function
array_map() function Convert all values in an array to lowercase or uppercase before making a judgment.
Sample code:
$array = array('apple', 'banana', 'orange'); $lower_array = array_map('strtolower', $array); if (in_array('apple', $lower_array)) { echo 'yes'; } else { echo 'no'; }
The output result is: yes
6. Use array_search() function and array_map() function
Similarly, use array_map( ) function can convert all the values in an array to lowercase or uppercase before searching.
Sample code:
$array = array('apple', 'banana', 'orange'); $lower_array = array_map('strtolower', $array); $key = array_search('Apple', $lower_array); if ($key !== false) { echo 'yes'; } else { echo 'no'; }
The output result is: yes
To sum up, you can use the in_array() function and array_search() function to determine whether a character is in the array. And the parameters of related functions are case-sensitive and other operations. In actual development, choosing the appropriate method according to the specific situation can improve code efficiency.
The above is the detailed content of How to determine whether a character is in an array in php. For more information, please follow other related articles on the PHP Chinese website!