Php in array

PHP Arrays, one of the interesting topic in PHP, in learning part of a view, since, it includes several direct PHP functions to work with arrays. In this article, we took one of those functions, PHP in_array(), to learn about it in detail.

In PHP, in_array() is used to check whether a value or sub array is the part of given master array or not. If the given value or sub-array exists in the master array, then in_array() will return TRUE, or false otherwise.


PHP in_array Syntax and Parameters

The following syntax shown will help us to use the in_array function in a PHP program. This function includes three parameters, where the third one is optional.


Parameters of PHP in_array() Function

  • $data_to_search – It could be a string, int, or an array. But, before PHP version 4.2.0, array data are not allowed for this first parameter of in_array().
  • $master_array – It accepts array considered as a master or collection, among which we need to search for a given data.
  • $strict_search_flag – This optional parameter will have boolean values. If TRUE this function will do a strict search by comparing the data types, otherwise doing a loose search, if it is FALSE.


  • Keeping the third parameter as TRUE is safe forever. Why because, if the master array contains 0, true/false or NULL as its entry, then, in_array will return unexpected results. For example,

    echo in_array('3', array(true,"one","two","three"));  

    This program will return true, even though there is no such entry in the master array. So, strict matching will solve this problem, by keeping the third parameter as TRUE.

  • Using this function, string matching will be done in case sensitive manner.

Other PHP Functions for Searching Arrays

PHP includes some other functions to search for a keyword or string over a master array as like as PHP in_array. These functions are,

  • array_key_exists()
  • array_search()

PHP Key Matching using array_key_exists()

We have seen that PHP in_array() function returns TRUE if there is match found between given data and the values of the master array. Similarly, array_key_exists() will do the same for searching keys or indices if the master array is an associative array.

Let us check the behavior of this function by using the following PHP code.

$master_assoc_array = array("id"=>1000,"name"=>"PHP");  echo array_key_exists("name",$master_assoc_array);  

In the above program, array_key_exists() will return TRUE, since, the given master associative array includes such key, as we have specified for the key search. And, if we search keys with respect to the nonassociative array, then we can find for numeric indices, which will be associated with each element of a PHP nonassociative array by default.

array_search() in PHP

This is equivalent PHP function as like as in_array() but differs with what it is returning. If any match found between given data and values of the master array, then, PHP array_search() will return the corresponding index of the entry with which the match is found, whereas, in_array() returns boolean value TRUE, instead.

The following PHP code will return the index of the given string with which it is associated in the master array.

$master_array = array("one","two","three");  echo "Array index of 'three' is " . array_search("three", $master);  

Since, the given master array is a non-associative array, as per the default numeric indices associated with the element of $master_array, the PHP print statement will return the following output to the browser.

Array index of 'three' is 2  

Other than returning index of the matched entry, array_search() is identical to PHP in_array, since it accepts the same set of three arguments, searches in case sensitive manner and allows strict matching. So, we can use any of these functions based on the requirements, like, if we want to get key index or simply want to check if match found.

This PHP code tutorial was published on August 22, 2013.

↑ Back to Top

Esta función falla con las letras acentuadas y con las eñes. Por tanto, no sirve para los caracteres UTF-8.
El siguiente código falla para na cadena = "María Mañas", no reconoce ni la "í" ni la "ñ":

    function validarNombreYApellidos ($cadena, $selector)
        /* Se admiten las letras (he puesto sólo las mayusculas,
             porque paso la cadena con el nombre o
             el apellido a mayúscula antes de hacer la comparación),
             las vocales acentuadas, la diéresis,
             las eñes, los espacios en blanco y el guión
            (para los apellidos compuestos)*/
        $caracteresPermitidos =
               array ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                          "N", "Ñ", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
                          "Y",  "Z", " ", "Á", "É", "Í", "Ó", "Ú", "Ü", "-");
        $correcto = true;

        // ¿La cadena está vacía?
        if (empty ($cadena))
            $correcto = false;
            $nombreOapellido = mb_strtoupper ($cadena, "utf-8");
            $longitudCadena = mb_strlen ($cadena, "utf-8");

            for ($i = 0; ($i < $longitudCadena) && $correcto; $i++)
                if (!in_array ($nombreOapellido [$i],
                    // Se ha encontrado un carácter no permitido
                    $correcto = false;
            return $correcto;

Уникальное имя радио в php while loop Yii изменить класс ошибкиHandler в config / main.php PHP: удаленный размер файла без загрузки файла Параметр функции со странным поведением кодировки в PHP Разница между вызовом нестатического метода статически и не статически Эффективно выбирайте n случайных элементов из массива PHP (без перетасовки) PHP – хранить информацию без базы данных NO как отправлять push-уведомления на iphone с помощью fcm (firebase console) в PHP? Что не так с этим кодом AS3 для связи с файлом PHP? Список изображений (01.png) и описания (01.txt) из каталога Вызывает ли вызов ob_end_clean () один раз в верхней части скрипта, гарантировать, что ob_flush () никогда не требуется? MySQL не удаляет записи как использовать тонкое перенаправление безмасляная рама, работающая только через cli Соответствие символов символов Unicode в PCRE / PHP

Small method i built for my Array module, after looking through the manual I wanted a small compact way of making a wildcard search through an arrays values, and returning only those that it found.


     * Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
     * @param    string        $string        Needle to find
     * @param    array        $array        Haystack to look through
     * @result    array                    Returns the elements that the $string was found in
function find ($string, $array = array ())
        foreach (
$array as $key => $value) {
            unset (
            if (
strpos($value, $string) !== false) {
$array[$key] = $value;

You May Also Like

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте как обрабатываются ваши данные комментариев.