php check array value in array

How to check if an array value exists?

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

12 Answers 12

You could use the PHP in_array function

By the way, you are assigning a value with the key say twice, hence your array will result in an array with only one value.

Using: in_array()

Here is output: The ‘prize_id’ element is in the array

Using: array_key_exists()

No output

In conclusion, array_key_exists() does not work with a simple array. Its only to find whether an array key exist or not. Use in_array() instead.

Here is more example:

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

To check if the index is defined: isset($something[‘say’])

You can test whether an array has a certain element at all or not with isset() or sometimes even better array_key_exists() (the documentation explains the differences). If you can’t be sure if the array has an element with the index ‘say’ you should test that first or you might get ‘warning: undefined index. ‘ messages.

As for the test whether the element’s value is equal to a string you can use == or (again sometimes better) the identity operator === which doesn’t allow type juggling.

in_array() is fine if you’re only checking but if you need to check that a value exists and return the associated key, array_search is a better option.

This will print «Key is 1»

Just use the PHP function array_key_exists()

Источник

How can I check if an array contains a specific value in php?

I have a PHP variable of type Array and I would like find out if it contains a specific value and let the user know that it is there. This is my array:

and I would like do something like:

What is the best way to do the above?

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

8 Answers 8

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

You need to use a search algorithm on your array. It depends on how large is your array, you have plenty of choices on what to use. Or you can use on of the built in functions:

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

Using dynamic variable for search in array

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

Following is how you can do this:

Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won’t work:

If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779

Not the answer you’re looking for? Browse other questions tagged php arrays or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

in_array

(PHP 4, PHP 5, PHP 7, PHP 8)

in_array — Checks if a value exists in an array

Description

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

Parameters

The searched value.

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

Return Values

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

Examples

Example #1 in_array() example

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

Example #2 in_array() with strict example

The above example will output:

Example #3 in_array() with an array as needle

The above example will output:

See Also

User Contributed Notes 38 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.

// First three make sense, last four do not

If you’re working with very large 2 dimensional arrays (eg 20,000+ elements) it’s much faster to do this.

Remember to only flip it once at the beginning of your code though!

# foo it is found in the array or one of its sub array.

For a case-insensitive in_array(), you can use array_map() to avoid a foreach statement, e.g.:

Determine whether an object field matches needle.

= array( new stdClass (), new stdClass () );
$arr [ 0 ]-> colour = ‘red’ ;
$arr [ 1 ]-> colour = ‘green’ ;
$arr [ 1 ]-> state = ‘enabled’ ;

in_array() may also return NULL if the second argument is NULL and strict types are off.

If the strict mode is on, then this code would end up with the TypeError

In a high-voted example, an array is given that contains, amongst other things, true, false and null, against which various variables are tested using in_array and loose checking.

If you have an array like:
$arr = array(0,1,2,3,4,5);

Add an extra if() to adrian foeder’s comment to make it work properly:

If you found yourself in need of a multidimensional array in_array like function you can use the one below. Works in a fair amount of time

This code will search for a value in a multidimensional array with strings or numbers on keys.

I just struggled for a while with this, although it may be obvious to others.

If you have an array with mixed type content such as:

?>

be sure to use the strict checking when searching for a string in the array, or it will match on the 0 int in that array and give a true for all values of needle that are strings strings.

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*:

?>

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 would like to add something to beingmrkenny at gmail dot com comparison post. After debugging a system, i discovered a security issue in our system and his post helped me find the problem.

In my additional testing i found out that not matter what you search for in an array, except for 0 and null, you get true as the result if the array contains true as the value.

Examples as php code :

Such the best practice in our case is to use strict mode. Which was not so obvious.

Kelvin’s case-insensitive in_arrayi is fine if you desire loose typing, but mapping strtolower onto the array will (attempt to) cast all array members to string. If you have an array of mixed types, and you wish to preserve the typing, the following will work:

// Note
// You can’t use wildcards and it does not check variable type
?>

A first idea for a function that checks if a text is in a specific column of an array.
It does not use in_array function because it doesn’t check via columns.
Its a test, could be much better. Do not use it without test.

Beware when using this function to validate user input:

$a = array(‘0’ => ‘Opt 1’, ‘1’ => ‘Opt 2’, ‘2’ => ‘Opt 3’);
$v = ‘sql injection’;
var_dump(in_array($v, array_keys($a)));

This will result : true;

If you need to find if a value in an array is in another array you can use the function:

The top voted notes talked about creating strict comparison function, because in_array is insufficient, because it has very lenient type checking (which is PHP default behaviour).

The thing is, in_array is already sufficient. Because as a good programmer, you should never have an array which contains ; all in one array anyway.

It’s better to fix how you store data and retrieve data from user, rather than fixing in_array() which is not broken.

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.

Recursive in array using SPL

If array contain at least one true value, in_array() will return true every times if it is not false or null

Be careful to use the strict parameter with truth comparisons of specific strings like «false»:

?>

The above example prints:

False is truthy.
False is not truthy.

This function is for search a needle in a multidimensional haystack:

When using numbers as needle, it gets tricky:

Note this behaviour (3rd statement):

in_array(0, array(42)) = FALSE
in_array(0, array(’42’)) = FALSE
in_array(0, array(‘Foo’)) = TRUE
in_array(‘0’, array(‘Foo’)) = FALSE

Watch out for this:

Yes, it seems that is_array thinks that a random string and 0 are the same thing.
Excuse me, that’s not loose checking, that’s drunken logic.
Or maybe I found a bug?

hope this function may be useful to you, it checks an array recursively (if an array has sub-array-levels) and also the keys, if wanted:

If you have a multidimensional array filled only with Boolean values like me, you need to use ‘strict’, otherwise in_array() will return an unexpected result.

Hope this helps somebody, cause it took me some time to figure this out.

If you search for numbers, in_array will convert any strings in your array to numbers, dropping any letters/characters, forcing a numbers-to-numbers comparison. So if you search for 1234, it will say that ‘1234abcd’ is a match. Example:

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 «ñ»:

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

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 «ñ»:

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

I needed a version of in_array() that supports wildcards in the haystack. Here it is:

$haystack = array( ‘*krapplack.de’ );
$needle = ‘www.krapplack.de’ ;

var_dump(in_array(‘invalid’, array(0,10,20)));
The above code gives true since the ‘invalid’ is getting converted to 0 and checked against the array(0,10,20)

but var_dump(in_array(‘invalid’, array(10,20))); gives ‘false’ since 0 not there in the array

A function to check an array of values within another array.

Second element ‘123’ of needles was found as first element of haystack, so it return TRUE.

If third parameter is not set to Strict then, the needle is found in haystack eventhought the values are not same. the limit behind the decimal seems to be 6 after which, the haystack and needle match no matter what is behind the 6th.

In PHP array function the in_array() function mainly used to check the item are available or not in array.

1. Non-strict validation
2. Strict validation

1. Non-strict validation:
This method to validate array with some negotiation. And it allow two parameters.

Note: the Example 1, we use only two parameter. Because we can’t mention `false` value. Because In default the in_array() take `false` as a boolean value.

In above example,
Example 1 : The `key1` is not value in the array. This is key of the array. So this scenario the in_array accept the search key as a value of the array.
Example 2: The value `577` is not in the value and key of the array. It is some similar to the value `579`. So this is also accepted.

So this reason this type is called non-strict function.

2. Strict validation
This method to validate array without any negotiation. And it have three parameters. If you only mention two parameter the `in_array()` function take as a non-strict validation.

This is return `true` only the search string is match exactly with the array value with case sensitivity.

Источник

array_key_exists

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

array_key_exists — Checks if the given key or index exists in the array

Description

array_key_exists() returns true if the given key is set in the array. key can be any value possible for an array index.

Parameters

An array with keys to check.

Return Values

Returns true on success or false on failure.

array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found.

Examples

Example #1 array_key_exists() example

Example #2 array_key_exists() vs isset()

isset() does not return true for array keys that correspond to a null value, while array_key_exists() does.

Notes

To check whether a property exists in an object, property_exists() should be used.

See Also

User Contributed Notes 38 notes

If you want to take the performance advantage of isset() while keeping the NULL element correctly detected, use this:

Benchmark (100000 runs):
array_key_exists() : 205 ms
is_set() : 35ms
isset() || array_key_exists() : 48ms

Note:
The code for this check is very fast, so you shouldn’t warp the code into a single function like below, because the overhead of calling a function dominates the overall performance.

function array_check(. )
<
return (isset(..) || array_key_exists(. ))
>

You’ll notice several notes on this page stating that isset() is significantly faster than array_key_exists(). This may be true except for one small hitch. isset() will return false for arrays keys that have there value set to NULL, which is therefore not entirely accurate.

= array();
$foo [ ‘bar’ ] = NULL ;

Beware that if the array passed to array_key_exists is NULL, the return value will also be NULL.

This is undocumented behaviour, moreover the documentation (and return typehint) suggest that the array_key_exists function only returns boolean value. But that’s not the case.

The way array_key_exists handles null, float, boolean, and ‘integer-representing string’ keys is inconsistent in itself and, in the case of bool and float, with the way these are converted when used as array offset.

array (
» => 1,
0 => 2,
1 => 3,
4 => 4,
’08’ => 5,
8 => 6,
)
null is a key.
false is not a key.
true is not a key.
4.6 is not a key.
«08» is a key.
«8» is a key.

Well, and you get this warning three times (on the bools and the float, but not on the null):

Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /var/www/php/test.php on line 6

The argument of array_key_exists() vs. isset() came up in the workplace today, so I conducted a little benchmark to see which is faster:

?>

On Windows, the output is similar to

array_key_exists(): 0.504 [82.895%] seconds
isset(): 0.104 [17.105%] seconds

On Mac or Linux, isset() is faster but only by a factor of approximately 1.5.

I’ve got a new take on the multi key function I would like to share.

Very simple case-insensitive array_key_exists:

bool (in_array(strtolower($needle), array_map(‘strtolower’, array_keys($haystack))))

array_key_exists doesn’t work with objects implementing ArrayAccess interface. It also ignores possible __get() method in such objects, despite the fact it accepts object as a second parameter. It works only with ‘real’ properties.

Here is an example with array_key_exists switching between content-types :

I took hours for me to debug, and I finally recognized that,

Or you will get no reply.

Rudi’s multidimensional array_key_exists function was not working for me, so i built one that is.
Enjoy.

Here is a little function for case sensitivity to elaborate on what was said by MarkL from ##php (Freenode) and mmanning at mdanderson dot org from this page:

Also, I’ve been running into issues with escaping for Regex, so I decided to give something like this a shot:

Regarding performance differences between isset() and array_key_exists(), the differences may be there, but the function are not always interchangable.

A little function which take an array as keys

Here’s a function to return a reference to the first array element that has a given key. The code works for multidimensional arrays:

I created this function that uses array key exist to compare a form and a table to see if something has changed.

This can be very helpfull if you need to update a table record from a form but you do not want to display all table fields.

/// it works like array_key_exists that can go deeper

$cidade = array(
‘redonda’ => array(
‘curta’ => ‘o seu filme’
),
‘quadrada’ => array(
‘longa’ => array(
‘azul’ => array(‘logo’,2,’mais’,2,’são’,4),
‘amarela’ => array(‘então’,3,’vezes’,2,’são’,6),
‘verde’ => array(‘senão’,100,’dividido por’,2,’é’,50)
),
‘extravagante’ => array(
‘vermelha’ => ‘chama atenção’,
‘vinho’ => ‘cor de uva’,
‘ocre’ => 1255
),
‘comprida’ => array(
‘amarela’ => ‘brasilia dos mamonas’,
‘branca’ => ‘bandeira da paz’,
‘preta e branca’ => ‘peças do xadrez’
)
),
‘oval’ => array(
‘conde’ => ‘lobo’
),
‘plana’ => array(
‘curta’ => array(
‘azul’ => array(‘e’,2,’mais’,2,’são’,4),
‘amarela’ => array(‘sim’,3,’vezes’,2,’são’,6),
‘verde’ => array(‘verdade’,100,’dividido por’,2,’é’,50)
)
)
);

/// if the tree you search for exists, it will print out ‘true’

Further research on this has turned up that the performance problems are a known, confirmed bug in PHP 5.1.x, and have been fixed in PHP builds after September 2006. You can find the bug report here: http://bugs.php.net/bug.php?id=38812

However, just because it’s a fixed bug doesn’t really change the conclusion. If you’re writing a script and there’s any chance it could be used on a PHP 5.1.x server, you should still avoid this function and use isset() or some other kind of test if you want it to run efficiently.

I saw some examples above for array_keys_exist() or functions to see if multiple keys exist in a given array and return false if any of them don’t.

Here is a simpler way to do this:

Источник

Check if string contains a value in array [duplicate]

I am trying to detect whether a string contains at least one URL that is stored in an array.

The string is entered by the user and submitted via PHP. On the confirmation page I would like to check if the URL entered is in the array.

I have tried the following:

No matter what is inputted the return is always «Match not found».

Is this the correct way of doing things?

15 Answers 15

Use stristr() or stripos() if you want to check case-insensitive.

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

This was a lot easier to do if all you want to do is find a string in an array.

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

Simple str_replace with count parameter would work here:

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

output

I think that a faster way is to use preg_match.

Here is a mini-function that search all values from an array in a given string. I use this in my site to check for visitor IP is in my permitted list on certain pages.

stripos function is not very strict. it’s not case sensitive or it can match a part of a word http://php.net/manual/ro/function.stripos.php

if you want that search to be case sensitive use strpos http://php.net/manual/ro/function.strpos.php

for exact match use regex (preg_match), check this guy answer https://stackoverflow.com/a/25633879/4481831

php check array value in array. Смотреть фото php check array value in array. Смотреть картинку php check array value in array. Картинка про php check array value in array. Фото php check array value in array

If not, you’d be better off using a regular expression to extract the domain from the string, and then use in_array() to check for a match.

The expression above could probably be improved (I’m not particularly knowledgeable in this area)

Here’s a demo

You can concatenate the array values with implode and a separator of | and then use preg_match to search for the value.

Источник

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

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