Php if var in list

list

Like array() , this is not really a function, but a language construct. list() is used to assign a list of variables in one operation. Strings can not be unpacked and list() expressions can not be completely empty.

Note:

Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0.

Parameters

Return Values

Returns the assigned array.

Changelog

Version Description
7.3.0 Support for reference assignments in array destructuring was added.
7.1.0 It is now possible to specify keys in list() . This enables destructuring of arrays with non-integer or non-sequential keys.

Examples

Example #1 list() examples

$info = array( ‘coffee’ , ‘brown’ , ‘caffeine’ );

// Listing all the variables
list( $drink , $color , $power ) = $info ;
echo » $drink is $color and $power makes it special.\n» ;

// Listing some of them
list( $drink , , $power ) = $info ;
echo » $drink has $power .\n» ;

// Or let’s skip to only the third one
list( , , $power ) = $info ;
echo «I need $power !\n» ;

// list() doesn’t work with strings
list( $bar ) = «abcde» ;
var_dump ( $bar ); // NULL
?>

Example #2 An example use of list()

$result = $pdo -> query ( «SELECT id, name FROM employees» );
while (list( $id , $name ) = $result -> fetch ( PDO :: FETCH_NUM )) echo «id: $id , name: $name \n» ;
>
?>

Example #3 Using nested list()

list( $a , list( $b , $c )) = array( 1 , array( 2 , 3 ));

Example #4 list() and order of index definitions

The order in which the indices of the array to be consumed by list() are defined is irrelevant.

$foo = array( 2 => ‘a’ , ‘foo’ => ‘b’ , 0 => ‘c’ );
$foo [ 1 ] = ‘d’ ;
list( $x , $y , $z ) = $foo ;
var_dump ( $foo , $x , $y , $z );

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(4) < [2]=>string(1) "a" ["foo"]=> string(1) "b" [0]=> string(1) "c" [1]=> string(1) "d" > string(1) "c" string(1) "d" string(1) "a"

Example #5 list() with keys

As of PHP 7.1.0 list() can now also contain explicit keys, which can be given as arbitrary expressions. Mixing of integer and string keys is allowed; however, elements with and without keys cannot be mixed.

$data = [
[ «id» => 1 , «name» => ‘Tom’ ],
[ «id» => 2 , «name» => ‘Fred’ ],
];
foreach ( $data as [ «id» => $id , «name» => $name ]) echo «id: $id , name: $name \n» ;
>
echo PHP_EOL ;
list( 1 => $second , 3 => $fourth ) = [ 1 , 2 , 3 , 4 ];
echo » $second , $fourth \n» ;

The above example will output:

id: 1, name: Tom id: 2, name: Fred 2, 4

See Also

  • each() — Return the current key and value pair from an array and advance the array cursor
  • array() — Create an array
  • extract() — Import variables into the current symbol table from an array
Читайте также:  Tf cpp min log level

User Contributed Notes 25 notes

Since PHP 7.1, keys can be specified

exemple :
$array = [ ‘locality’ => ‘Tunis’ , ‘postal_code’ => ‘1110’ ];

list( ‘postal_code’ => $zipCode , ‘locality’ => $locality ) = $array ;

print $zipCode ; // will output 1110
print $locality ; // will output Tunis
?>

In PHP 7.1 we can do the following:

[ $a , $b , $c ] = [ ‘a’ , ‘b’ , ‘c’ ];
?>

Before, we had to do:

$info = array(‘kawa’, ‘brązowa’, ‘kofeina’);
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);

One thing to note here is that if you define the array earlier, e.g.:
$a = [0, 0, 0];

the indexes will be kept in the correct order:

Thought that it was worth mentioning.

As noted, list() will give an error if the input array is too short. This can be avoided by array_merge()’ing in some default values. For example:

$parameter = ‘name’ ;
list( $a , $b ) = array_merge ( explode ( ‘=’ , $parameter ), array( true ) );
?>

However, you will have to array_merge with an array long enough to ensure there are enough elements (if $parameter is empty, the code above would still error).

An alternate approach would be to use array_pad on the array to ensure its length (if all the defaults you need to add are the same).

$parameter = ‘bob-12345’ ;
list( $name , $id , $fav_color , $age ) = array_pad ( explode ( ‘-‘ , $parameter ), 4 , » );
var_dump ( $name , $id , $fav_color , $age );
/* outputs
string(3) «bob»
string(5) «12345»
string(0) «»
string(0) «»
*/
?>

The example states the following:
// list() doesn’t work with strings
list( $bar ) = «abcde» ;
var_dump ( $bar );
// output: NULL
?>

If the string is in a variable however, it seems using list() will treat the string as an array:
$string = «abcde» ;
list( $foo ) = $string ;
var_dump ( $foo );
// output: string(1) «a»
?>

/**
* It seems you can skip listed values.
* Here’s an example to show what I mean.
*
* FYI works just as well with PHP 7.1 shorthand list syntax.
* Tested against PHP 5.6.30, 7.1.5
*/
$a = [ 1 , 2 , 3 , 4 ];

// this is quite normal use case for list
echo «Unpack all values\n» ;
list( $v1 , $v2 , $v3 , $v4 ) = $a ;
echo » $v1 , $v2 , $v3 , $v4 \n» ;
unset( $v1 , $v2 , $v3 , $v4 );

// this is what I mean:
echo «Skip middle\n» ;
list( $v1 , , , $v4 ) = $a ;
echo » $v1 , $v2 , $v3 , $v4 \n» ;
unset( $v1 , $v2 , $v3 , $v4 );

echo «Skip beginning\n» ;
list( , , $v3 , $v4 ) = $a ;
echo » $v1 , $v2 , $v3 , $v4 \n» ;
unset( $v1 , $v2 , $v3 , $v4 );

echo «Skip end\n» ;
list( $v1 , $v2 , , ) = $a ;
echo » $v1 , $v2 , $v3 , $v4 \n» ;
unset( $v1 , $v2 , $v3 , $v4 );

echo «Leave middle\n» ;
list( , $v2 , $v3 , ) = $a ;
echo » $v1 , $v2 , $v3 , $v4 \n» ;
unset( $v1 , $v2 , $v3 , $v4 );

list() can be used with foreach

$array = [[ 1 , 2 ], [ 3 , 4 ], [ 5 , 6 ]];

foreach( $array as list( $odd , $even )) echo » $odd is odd; $even is even» , PHP_EOL ;
>
?>

The output:
===
1 is odd; 2 is even
3 is odd; 4 is even
5 is odd; 6 is even

Читайте также:  Document root folder php

The list construct seems to look for a sequential list of indexes rather taking elements in sequence. What that obscure statement means is that if you unset an element, list will not simply jump to the next element and assign that to the variable but will treat the missing element as a null or empty variable:

The list() definition won’t throw an error if your array is longer then defined list.

list( $a , $b , $c ) = array( «a» , «b» , «c» , «d» );

var_dump ( $a ); // a
var_dump ( $b ); // b
var_dump ( $c ); // c
?>

Don’t miss simple array pattern matching since php 7

[ $a ] = [ ‘hello!’ ];
var_dump ( $a ); // ‘hello!’

$arr = [ 4 => 50 ];
[ 4 => $fifty ] = $arr ;
var_dump ( $fifty ); // 50

$multidimensionalArray = [[ ‘id’ => 15 , ’email’ => ‘diyor024@gmail.com’ ]];
[[ ‘id’ => $id , ’email’ => $email ]] = $multidimensionalArray ;
var_dump ( $id , $email ); // 15 diyor024@gmail.com

For PHP 7.1 on, the documentation states that integer and string keys can be mixed, but that elements with and without keys cannot. Here is an example, using data from getimagesize() with mixed keys:

$data =[
0 => 160 ,
1 => 120 ,
2 => 2 ,
3 => ‘width=»160″ height=»120″‘ ,
‘mime’ => ‘image/jpeg’
];
list( 0 => $width , 1 => $height , 2 => $type , 3 => $dimensions , ‘mime’ => $mime )= $data ;
?>

Here, the numeric keys also need to be specified, as if the whole array is treated as an associative array.

As noted elsewhere, the list() operator can be written in array format:

[ 0 => $width , 1 => $height , 2 => $type , 3 => $dimensions , ‘mime’ => $mime ]= $data ;
?>

Setting it like does _not_ raise an E_NOTICE (or other error) and afaics effectively equals an https://php.net/function.unset of $var1,$varN.

I note this as contrasting with the fact that PHP triggers an E_NOTICE about «Undefined offset» «if there aren’t enough array elements to fill the list()», as attow documented for https://php.net/control-structures.foreach#control-structures.foreach.list and here only noted in https://php.net/function.list#122951 by Mardaneus.

For completeness, a bash(1) (v5.0 or 4.3 on macos10.13) cli test producing the same result for all my PHP-versions (installed via macports.org) follows. It’s also tested with php7.3 using bash5.0 on Debian10:
bash —noprofile —norc -c ‘for php in php,>;do for literal in «array()» null;do echo -n $php …=$literal:&&$php -n -d error_reporting=E_ALL -r «var_dump(list(\$var)=$literal);»;done;done’

# Above produces the same result pairs per version from:
php53 …=array():
Notice: Undefined offset: 0 in Command line code on line 1
array(0) >
# . to:
php73 …=null:NULL

This is something I haven’t seen in documentation.

Since PHP 7.1, you can use short-hand list unpacking using square brackets, just like short-hand array declaration:

// short-hand array definition
[ $a , $b , $c ] = $foo ;
echo $a ; // displays «a»

// it’s same like:
list( $x , $y , $z ) = $foo ;
echo $x ; // displays «a»

Источник

Дополнения к функции in_array()

PHP-функция in_array() проверяет, присутствует ли в массиве значение:

$array = array("Mac", "NT", "Irix", "Linux"); if (in_array('Irix', $array))

Но в некоторых моментах её будет не достаточно, далее подробнее:

Проверка сразу нескольких значений в массиве

Если требуется проверить наличие сразу нескольких значений в массиве – функция in_array_all() .

function in_array_all($needles, $haystack)

Пример использования:

$array = array('Mac', 'NT', 'Irix', 'Linux'); if (in_array_all(array('Mac', 'Win'), $array)) < echo 'true'; >else < echo 'false'; // Выведется false т.к. в $array нет 'Win' >

Одно из нескольких значений в массиве

Если требуется проверить вхождение хотя бы одного из нескольких значений, подойдет функция in_array_any() .

function in_array_any($needles, $haystack)

Пример использования:

$array = array('Mac', 'NT', 'Irix', 'Linux'); if (in_array_any(array('Mac', 'Win'), $array)) < echo 'true'; // Выведется true т.к. в $array есть 'Mac' >else

in_array для многомерного массива

Для поиска значения в многомерном массиве поможет функция in_array_r() :

function in_array_r($needle, $haystack, $strict = false) < foreach ($haystack as $item) < if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) < return true; >> return false; >

Пример использования:

$array = array( 0 => array('Mac'), 1 => array('NT'), 2 => array('Irix'), 3 => array('Linux') ); if (in_array_r('Mac', $array)) < echo 'true'; // Выведется true >else

Комментарии

Другие публикации

Сортировка массивов

В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим.

Читайте также:  Php date завтрашний день

PHP функции для checked и selected

Две мини функции которые облегчают выделения полей select, radio и checkbox до и после отправки форм.

Автоматическое сжатие и оптимизация картинок на сайте

Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет.

Источник

PHP in_array() Function

Search for the value «Glenn» in an array and output some text:

$people = array(«Peter», «Joe», «Glenn», «Cleveland»);

if (in_array(«Glenn», $people))
echo «Match found»;
>
else
echo «Match not found»;
>
?>

Definition and Usage

The in_array() function searches an array for a specific value.

Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

Syntax

Parameter Values

Parameter Description
search Required. Specifies the what to search for
array Required. Specifies the array to search
type Optional. If this parameter is set to TRUE, the in_array() function searches for the search-string and specific type in the array.

Technical Details

Return Value: Returns TRUE if the value is found in the array, or FALSE otherwise
PHP Version: 4+
PHP Changelog: PHP 4.2: The search parameter may now be an array

More Examples

Example

$people = array(«Peter», «Joe», «Glenn», «Cleveland», 23);

if (in_array(«23», $people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>
if (in_array(«Glenn»,$people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>

if (in_array(23,$people, TRUE))
echo «Match found
«;
>
else
echo «Match not found
«;
>
?>

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью