Php if in array declaration

Php if in array declaration

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23

but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :

$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>

Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.

Источник

PHP in_array

Summary: in this tutorial, you will learn how to use the PHP in_array() function to check if a value exists in an array.

Introduction to the PHP in_array() function

The in_array() function returns true if a value exists in an array. Here’s the syntax of the in_array() function:

in_array ( mixed $needle , array $haystack , bool $strict = false ) : boolCode language: PHP (php)
  • $needle is the searched value.
  • $haystack is the array to search.
  • $strict if the $strict sets to true , the in_array() function will use the strict comparison.

The in_array() function searches for the $needle in the $haystack using the loose comparison ( == ). To use the strict comparison ( === ), you need to set the $strict argument to true .

If the value to check is a string, the in_array() function will search for it case-sensitively.

The in_array() function returns true if the $needle exists in the $array ; otherwise, it returns false .

PHP in_array() function examples

Let’s take some examples of using the in_array() function.

1) Simple PHP in_array() function examples

The following example uses the in_array() function to check if the value ‘update’ is in the $actions array:

 $actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('update', $actions); var_dump($result); // bool(true)Code language: HTML, XML (xml)

The following example returns false because the publish value doesn’t exist in the $actions array:

 $actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('publish', $actions); var_dump($result); // bool(false) Code language: HTML, XML (xml)

The following example returns false because the value ‘New’ doesn’t exist in the $actions array. Note that the in_array() compares the strings case-sensitively:

 $actions = [ 'new', 'edit', 'update', 'view', 'delete', ]; $result = in_array('New', $actions); var_dump($result); // bool(false) Code language: HTML, XML (xml)

2) Using PHP in_array() function with the strict comparison example

The following example uses the in_array() function to find the number 15 in the $user_ids array. It returns true because the in_array() function compares the values using the loose comparison ( == ):

 $user_ids = [10, '15', '20', 30]; $result = in_array(15, $user_ids); var_dump($result); // bool(true)Code language: HTML, XML (xml)

To use the strict comparison, you pass false to the third argument ( $strict ) of the in_array() function as follows:

 $user_ids = [10, '15', '20', 30]; $result = in_array(15, $user_ids, true); var_dump($result); // bool(false)Code language: HTML, XML (xml)

This time the in_array() function returns false instead.

3) Using PHP in_array() function with the searched value is an array example

The following example uses the in_array() function with the searched value is an array:

 $colors = [ ['red', 'green', 'blue'], ['cyan', 'magenta', 'yellow', 'black'], ['hue', 'saturation', 'lightness'] ]; if (in_array(['red', 'green', 'blue'], $colors)) < echo 'RGB colors found'; > else < echo 'RGB colors are not found'; >Code language: HTML, XML (xml)

4) Using PHP in_array() function with an array of objects example

The following defines the Role class that has two properties $id and $name :

 class Role < private $id; private $name; public function __construct($id, $name) < $this->id = $id; $this->name = $name; > >Code language: HTML, XML (xml)

This example illustrates how to use the in_array() function to check if a Role object exists in an array of Role objects:

 // Role class $roles = [ new Role(1, 'admin'), new Role(2, 'editor'), new Role(3, 'subscribe'), ]; if (in_array(new Role(1, 'admin'), $roles)) < echo 'found it'; >Code language: HTML, XML (xml)

If you set the $strict to true , the in_array() function will compare objects using their identities instead of values. For example:

// Role class $roles = [ new Role(1, 'admin'), new Role(2, 'editor'), new Role(3, 'subscribe'), ]; if (in_array(new Role(1, 'admin'), $roles, true)) < echo 'found it!'; > else < echo 'not found!'; >Code language: PHP (php)

Summary

Источник

in_array

Ищет в haystack значение needle . Если strict не установлен, то при поиске будет использовано нестрогое сравнение.

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

Замечание:

Если needle — строка, сравнение будет произведено с учетом регистра.

Если третий параметр strict установлен в TRUE тогда функция in_array() также проверит соответствие типов параметра needle и соответствующего значения массива haystack .

Возвращаемые значения

Возвращает TRUE , если needle был найден в массиве, и FALSE в обратном случае.

Примеры

Пример #1 Пример использования in_array()

$os = array( «Mac» , «NT» , «Irix» , «Linux» );
if ( in_array ( «Irix» , $os )) echo «Нашел Irix» ;
>
if ( in_array ( «mac» , $os )) echo «Нашел mac» ;
>
?>

Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:

Пример #2 Пример использования in_array() с параметром strict

if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ найдено со строгой проверкой\n» ;
>

if ( in_array ( 1.13 , $a , true )) echo «1.13 найдено со строгой проверкой\n» ;
>
?>

Результат выполнения данного примера:

1.13 найдено со строгой проверкой

Пример #3 Пример использования in_array() с массивом в качестве параметра needle

if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ найдено\n» ;
>

if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ найдено\n» ;
>

if ( in_array ( ‘o’ , $a )) echo «‘o’ найдено\n» ;
>
?>

Результат выполнения данного примера:

Смотрите также

  • array_search() — Осуществляет поиск данного значения в массиве и возвращает соответствующий ключ в случае удачи
  • isset() — Определяет, была ли установлена переменная значением отличным от NULL
  • array_key_exists() — Проверяет, присутствует ли в массиве указанный ключ или индекс

Источник

Читайте также:  About casting in java
Оцените статью