Php if array has one element

How to Get the First Element of an Array in PHP?

Get First Element of an Array With Sequential Numeric Indexes

It’s fairly easy and straightforward to get the first element of a sequential array in PHP. Consider for example the following array:

$sequentialArray = ['foo', 'bar', 'baz'];

Accessing the First Element of Array Directly:

echo $sequentialArray[0] ?? ''; // output: 'foo'

By using ?? (the null coalescing operator) you can return the first index if it’s set and not null, or return an empty string otherwise.

Using list() :

// PHP 4+ list($first) = $sequentialArray; // or, alternatively in PHP 7.1+ [$first] = $sequentialArray; echo $first; // output: 'foo'

For a non-sequential array this would throw an error because list() tries to unpack array values sequentially (starting from the first index — i.e. 0 ). However, starting from PHP 7.1, you can specify the specific key you’re looking to unpack but we’re not covering that since it’s not within the scope of this article.

Get First Element of an Out-Of-Order or Non-Sequential Array

In PHP, there are a number of ways you could access the value of the first element of an out-of-order (or non-sequential) array. Please note that we’ll be using the following array for all the examples that follow:

$names = [9 => 'john', 15 => 'jane', 22 => 'wayne'];

Using reset() :

The PHP reset() function not only resets the internal pointer of the array to the start of the array, but also returns the first array element, or false if the array is empty. This method has a simple syntax and support for older PHP versions:

// PHP 4+ echo reset($names); // output: "john"

Be careful when resetting the array pointer as each array only has one internal pointer and you may not always want to reset it to point to the start of the array.

Without Resetting the Original Array:

If you do not wish to reset the internal pointer of the array, you can work around it by creating a copy of the array simply by assigning it to a new variable before the reset() function is called, like so:

$namesCopy = $names; next($names); // move array pointer to 2nd element echo reset($namesCopy); // output: "john" echo current($names); // output: "jane"

As you can see from the results, we’ve obtained the first element of the array without affecting the original.

Using array_slice() :

// PHP 5.4+ echo array_slice($names, 0, 1)[0]; // output: "john"

Please note that by default array_slice() reorders and resets the numeric array indices. This can be changed however, by specifying the fourth parameter preserve_keys as true .

The advantage to using this approach is that it doesn’t modify the original array. However, on the flip side there could potentially be an array offset problem when the input array is empty. To resolve that, since our array only has one element, we could use the following methods to return the first (also the only) element:

// PHP 4+ $namesCopy = array_slice($names, 0, 1); echo array_shift($namesCopy); // output: null if array is empty echo array_pop($namesCopy); // output: null if array is empty echo implode($namesCopy); // output: '' if array is empty // PHP 7+ echo $names_copy[0] ?? ''; // output: '' if array index is not set or its value is null
  • You must note though that using array_shift() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged.
  • Using both array_shift() and array_pop() resets the array pointer of the input array after use, but in our case that doesn’t matter since we’re using a copy of the original array, that too with only a single element.
Читайте также:  Html вставить документ word в

Using array_values() :

// PHP 5.4+ echo array_values($names)[0]; // output: "john"

This method may only be useful if the array is known to not be empty.

In PHP 7+, we can use ?? (the null coalescing operator) to return the first index if it’s set and not null, or return an empty string otherwise. For example:

// PHP 7+ echo array_values($names)[0] ?? '';

Using array_reverse() :

// PHP 4+ array_pop(array_reverse($names)); // output: "john"
  • By default array_reverse() will reset all numerical array keys to start counting from zero while literal keys will remain unchanged unless a second parameter preserve_keys is specified as true .
  • This method is not recommended as it may do unwanted longer processing on larger arrays to reverse them prior to getting the first value.

Using foreach Loop:

We can simply make use of the foreach loop to go one round and immediately break (or return ) after we get the first value of the array. Consider the code below:

// PHP 4+ foreach ($names as $name) < echo $name; break; // break loop after first iteration >// or the shorter form foreach ($names as $name) break; // break loop after first iteration echo $name; // output: 'john'

Although it takes up a few lines of code, this would be the fastest way as it’s using the language construct foreach rather than a function call (which is more expensive).

This could be written as a reusable function as well:

function array_first_value(array $arr) < foreach ($arr as $fv) < return $fv; >return null; // return null if array is empty >

Hope you found this post useful. It was published 28 Jul, 2016 (and was last revised 31 May, 2020 ). Please show your love and support by sharing this post.

Источник

in_array

Searches for needle in haystack using loose comparison unless strict is set.

Parameters

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack .

Note:

Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior.

Return Values

Returns true if needle is found in the array, false otherwise.

Читайте также:  Java send event to listener

Examples

Example #1 in_array() example

$os = array( «Mac» , «NT» , «Irix» , «Linux» );
if ( in_array ( «Irix» , $os )) echo «Got Irix» ;
>
if ( in_array ( «mac» , $os )) echo «Got mac» ;
>
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Example #2 in_array() with strict example

if ( in_array ( ‘12.4’ , $a , true )) echo «‘12.4’ found with strict check\n» ;
>

if ( in_array ( 1.13 , $a , true )) echo «1.13 found with strict check\n» ;
>
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

if ( in_array (array( ‘p’ , ‘h’ ), $a )) echo «‘ph’ was found\n» ;
>

if ( in_array (array( ‘f’ , ‘i’ ), $a )) echo «‘fi’ was found\n» ;
>

if ( in_array ( ‘o’ , $a )) echo «‘o’ was found\n» ;
>
?>

The above example will output:

See Also

  • array_search() — Searches the array for a given value and returns the first corresponding key if successful
  • isset() — Determine if a variable is declared and is different than null
  • array_key_exists() — Checks if the given key or index exists in the array

User Contributed Notes 8 notes

Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP’s leniency on variable types, but in «real-life» is almost useless.

The solution is to use the strict checking option.

$array = array(
‘egg’ => true ,
‘cheese’ => false ,
‘hair’ => 765 ,
‘goblins’ => null ,
‘ogres’ => ‘no ogres allowed in this array’
);

// Loose checking — return values are in comments

// First three make sense, last four do not

in_array ( null , $array ); // true
in_array ( false , $array ); // true
in_array ( 765 , $array ); // true
in_array ( 763 , $array ); // true
in_array ( ‘egg’ , $array ); // true
in_array ( ‘hhh’ , $array ); // true
in_array (array(), $array ); // true

in_array ( null , $array , true ); // true
in_array ( false , $array , true ); // true
in_array ( 765 , $array , true ); // true
in_array ( 763 , $array , true ); // false
in_array ( ‘egg’ , $array , true ); // false
in_array ( ‘hhh’ , $array , true ); // false
in_array (array(), $array , true ); // false

I got an unexpected behavior working with in_array. I’m using following code:

// .
$someId = getSomeId (); // it gets generated/fetched by another service, so I don’t know what value it will have. P.S.: it’s an integer

// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = [‘dataOne’, ‘dataTwo’];
if ( in_array ( $someId , $anyArray )) // do some work
>
// .
?>

With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.

It took me quite some time to find out what’s going on.

I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

$needle = array(
‘fruit’ => ‘banana’ , ‘vegetable’ => ‘carrot’
);

$haystack = array(
array( ‘vegetable’ => ‘carrot’ , ‘fruit’ => ‘banana’ ),
array( ‘fruit’ => ‘apple’ , ‘vegetable’ => ‘celery’ )
);

Читайте также:  Калькулятор имт python sololearn

echo in_array ( $needle , $haystack , true ) ? ‘true’ : ‘false’ ;
// Output is ‘false’

echo in_array ( $needle , $haystack ) ? ‘true’ : ‘false’ ;
// Output is ‘true’

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether ‘strict’ is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.

I’d like to point out that, if you’re using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.

From what I’ve tested, the function works correctly:
if the array is filled with strings and you’re searching for a string;
if the array is filled with Enums and you’re searching for an Enum.

Here is a recursive in_array function:

$myNumbers = [
[ 1 , 2 , 3 , 4 , 5 ],
[ 6 , 7 , 8 , 9 , 10 ],
];

$array = [
‘numbers’ => $myNumbers
];

// Let’s try to find number 7 within $array
$hasNumber = in_array ( 7 , $array , true ); // bool(false)
$hasNumber = in_array_recursive ( 7 , $array , true ); // bool(true)

function in_array_recursive ( mixed $needle , array $haystack , bool $strict ): bool
foreach ( $haystack as $element ) if ( $element === $needle ) return true ;
>

$isFound = false ;
if ( is_array ( $element )) $isFound = in_array_recursive ( $needle , $element , $strict );
>

if ( $isFound === true ) return true ;
>
>

If you’re creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it’s much faster.

$slow = array( ‘apple’ , ‘banana’ , ‘orange’ );

if ( in_array ( ‘banana’ , $slow ))
print( ‘Found it!’ );

$fast = array( ‘apple’ => ‘apple’ , ‘banana’ => ‘banana’ , ‘orange’ => ‘orange’ );

if (isset( $fast [ ‘banana’ ]))
print( ‘Found it!’ );

Источник

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() — Проверяет, присутствует ли в массиве указанный ключ или индекс

Источник

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