php проверить что это массив
Проверка на массив, на наличие элементов и на пустоту в PHP
В этой статье будем делать различные проверки массива. В том числе проверим является ли переменная массивом, а так же проверим есть ли у ключей массива пустые значения. Будем двигаться от простого к более сложному. И первое, что можно сделать, это проверить на массив. Для этого нам помоет встроенная в язык PHP функция is_array. Разберем небольшой пример.
$arr = [‘id’, ‘name’, ’email’]; // Массив элементов if(is_array($arr))< echo 'Это массив'; >else
Функция вернет true, если это массив и false — если не массив. Это простой пример и сложностей возникнуть не должно. Перейдем к следующему примеру.
Проверка массива на пустоту и пустые элементы в PHP
Функция empty сработает только в том случае, когда в массиве нет вообще никаких элементов. Поэтому ее лучше не использовать при проверке массивов. В этом случае нам поможет еще одна функция — array_diff. С ее помощью мы сравним исходный массив с другим массивом и в случае расхождения выведем элементы массива, которые не совпадают. Может быть немного сумбурно и не понятно, но давайте разберем на примере.
array(8) < [0]=>string(4) «name» [1]=> string(0) «» [2]=> string(3) «num» [3]=> [4]=> string(0) «» [5]=> [6]=> string(4) «Alex» [7]=> string(0) «» > array(3) < [0]=>string(4) «name» [2]=> string(3) «num» [6]=> string(4) «Alex» >
Функция пропустит все пустые элемент массива, в том числе NULL и false и выведет только те, в которых что-то есть. Мы так же можем проверить какой именно элемент массива был пустой с помощью цикла for.
array(4) < ["age"]=>int(34) [«name»]=> string(4) «Ivan» [«city»]=> string(0) «» [«number»]=> string(0) «» > array(2) < ["age"]=>int(34) [«name»]=> string(4) «Ivan» >
Проверить наличие элемента в массиве
Для этих целей подойдет функция in_array. Она проверяет на присутствие в массиве значения.
Первым аргументом указываем что будем искать, вторым — где. На этом по работе с массивами окончен. Надеюсь, что вам в нем все было понятно. Но если остались какие-то вопросы, задавайте их в комментариях.
array
(PHP 4, PHP 5, PHP 7, PHP 8)
array — Создаёт массив
Описание
Создаёт массив. Подробнее о массивах читайте в разделе Массивы.
Список параметров
Наличие завершающей запятой после последнего элемента массива, несмотря на некоторую необычность, является корректным синтаксисом.
Возвращаемые значения
Примеры
Последующие примеры демонстрируют создание двухмерного массива, определение ключей ассоциативных массивов и способ генерации числовых индексов для обычных массивов, если нумерация начинается с произвольного числа.
Пример #1 Пример использования array()
Пример #2 Автоматическая индексация с помощью array()
Результат выполнения данного примера:
Этот пример создаёт массив, нумерация которого начинается с 1.
Результат выполнения данного примера:
Как и в Perl, вы имеете доступ к значениям массива внутри двойных кавычек. Однако в PHP нужно заключить ваш массив в фигурные скобки.
Пример #4 Доступ к массиву внутри двойных кавычек
Примечания
Смотрите также
User Contributed Notes 38 notes
As of PHP 5.4.x you can now use ‘short syntax arrays’ which eliminates the need of this function.
So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an label. So, with this function, if only a single array is passed to the function (i.e. «arrayToSelect($stateList)») then it will simply spit out a bunch of » » elements. On the other hand, if two arrays are passed to it, the second array becomes a «key» for translating the first array.
Here’s a further example:
$countryList = array(
‘CA’ => ‘Canada’,
‘US’ => ‘United States’);
$stateList[‘CA’] = array(
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘AB’ => ‘Alberta’,
‘BC’ => ‘British Columbia’,
‘MB’ => ‘Manitoba’,
‘NB’ => ‘New Brunswick’,
‘NL’ => ‘Newfoundland/Labrador’,
‘NS’ => ‘Nova Scotia’,
‘NT’ => ‘Northwest Territories’,
‘NU’ => ‘Nunavut’,
‘ON’ => ‘Ontario’,
‘PE’ => ‘Prince Edward Island’,
‘QC’ => ‘Quebec’,
‘SK’ => ‘Saskatchewan’,
‘YT’ => ‘Yukon’);
$stateList[‘US’] = array(
‘AL’ => ‘Alabama’,
‘AK’ => ‘Alaska’,
‘AZ’ => ‘Arizona’,
‘AR’ => ‘Arkansas’,
‘CA’ => ‘California’,
‘CO’ => ‘Colorado’,
‘CT’ => ‘Connecticut’,
‘DE’ => ‘Delaware’,
‘DC’ => ‘District of Columbia’,
‘FL’ => ‘Florida’,
‘GA’ => ‘Georgia’,
‘HI’ => ‘Hawaii’,
‘ID’ => ‘Idaho’,
‘IL’ => ‘Illinois’,
‘IN’ => ‘Indiana’,
‘IA’ => ‘Iowa’,
‘KS’ => ‘Kansas’,
‘KY’ => ‘Kentucky’,
‘LA’ => ‘Louisiana’,
‘ME’ => ‘Maine’,
‘MD’ => ‘Maryland’,
‘MA’ => ‘Massachusetts’,
‘MI’ => ‘Michigan’,
‘MN’ => ‘Minnesota’,
‘MS’ => ‘Mississippi’,
‘MO’ => ‘Missouri’,
‘MT’ => ‘Montana’,
‘NE’ => ‘Nebraska’,
‘NV’ => ‘Nevada’,
‘NH’ => ‘New Hampshire’,
‘NJ’ => ‘New Jersey’,
‘NM’ => ‘New Mexico’,
‘NY’ => ‘New York’,
‘NC’ => ‘North Carolina’,
‘ND’ => ‘North Dakota’,
‘OH’ => ‘Ohio’,
‘OK’ => ‘Oklahoma’,
‘OR’ => ‘Oregon’,
‘PA’ => ‘Pennsylvania’,
‘RI’ => ‘Rhode Island’,
‘SC’ => ‘South Carolina’,
‘SD’ => ‘South Dakota’,
‘TN’ => ‘Tennessee’,
‘TX’ => ‘Texas’,
‘UT’ => ‘Utah’,
‘VT’ => ‘Vermont’,
‘VA’ => ‘Virginia’,
‘WA’ => ‘Washington’,
‘WV’ => ‘West Virginia’,
‘WI’ => ‘Wisconsin’,
‘WY’ => ‘Wyoming’);
in_array
(PHP 4, PHP 5, PHP 7, PHP 8)
in_array — Проверяет, присутствует ли в массиве значение
Описание
Список параметров
Возвращаемые значения
Примеры
Пример #1 Пример использования in_array()
Второго совпадения не будет, потому что in_array() регистрозависима, таким образом, программа выведет:
Пример #2 Пример использования in_array() с параметром strict
Результат выполнения данного примера:
Пример #3 Пример использования in_array() с массивом в качестве параметра needle
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 39 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’ ;
If you need to find if a value in an array is in another array you can use the function:
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
This code will search for a value in a multidimensional array with strings or numbers on keys.
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
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.
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.
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:
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.
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.
// Note
// You can’t use wildcards and it does not check variable type
?>
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;
I tried to use in_array in combination with array_colum, here below a sample:
It seems to work right
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.
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
It’s better to fix how you store data and retrieve data from user, rather than fixing in_array() which is not broken.
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
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»);
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:
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
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»);
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.
Как проверить массив PHP, чтобы помочь своему другу
Дата публикации: 2016-12-28
Зачем проверять?
Программный код, как и человека (если не доверяете ему), лучше проверить. А то случившийся из-за излишней доверчивости (или безалаберности) разработчика баг может негативно сказаться на работоспособности всего приложения. Причем это может быть не только обидно, но и чревато:
Пострадает репутация авторитет всей команды разработчиков.
Не получите деньги за проект – созданное вами решение не пройдет тестирование.
Время на переделку – а это снова связано с финансовыми потерями.
Бесплатный курс по PHP программированию
Освойте курс и узнайте, как создать динамичный сайт на PHP и MySQL с полного нуля, используя модель MVC
В курсе 39 уроков | 15 часов видео | исходники для каждого урока
В общем, проверять нужно любой программный код. Именно поэтому в любом языке «навалом» различных встроенных функций, начинающихся с префикса is. Не является исключением и PHP.
Эти функции чаще всего возвращают значение типа bool. С их помощью удобно проверять код (переменные) на соответствие каким-либо условием. Например, можно удостовериться, что переменная является массивом. Для этого применим функцию is_array():
Массивы
User Contributed Notes 17 notes
For newbies like me.
Creating new arrays:-
//Creates a blank array.
$theVariable = array();
//Creates an array with elements.
$theVariable = array(«A», «B», «C»);
//Creating Associaive array.
$theVariable = array(1 => «http//google.com», 2=> «http://yahoo.com»);
//Creating Associaive array with named keys
$theVariable = array(«google» => «http//google.com», «yahoo»=> «http://yahoo.com»);
Note:
New value can be added to the array as shown below.
$theVariable[] = «D»;
$theVariable[] = «E»;
To delete an individual array element use the unset function
output:
Array ( [0] => fileno [1] => Array ( [0] => uid [1] => uname ) [2] => topingid [3] => Array ( [0] => touid [1] => Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => 3 [1] => 4 ) ) [2] => touname ) )
when I hope a function string2array($str), «spam2» suggest this. and It works well
hope this helps us, and add to the Array function list
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode. (Note that this probably adds a touch of overhead, but it sure does look nicer.) You can of course add as many levels and as much formatting as you’d like to the string you then decode. Don’t forget that json requires » around values, not ‘!! (So, you can’t enclose the json string with » and use ‘ inside the string.)
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can ‘stack’ an array in one pass, using one loop, like this:
$node [ ‘leaf’ ][ 1 ][ ‘title’ ] = ‘I am node one.’ ;
$node [ ‘leaf’ ][ 2 ][ ‘title’ ] = ‘I am node two.’ ;
$node [ ‘leaf’ ][ 3 ][ ‘title’ ] = ‘I am node three.’ ;
$node [ ‘leaf’ ][ 4 ][ ‘title’ ] = ‘I am node four.’ ;
$node [ ‘leaf’ ][ 5 ][ ‘title’ ] = ‘I am node five.’ ;
Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
If an array item is declared with key as NULL, array key will automatically be converted to empty string », as follows:
A small correction to Endel Dreyer’s PHP array to javascript array function. I just changed it to show keys correctly:
function array2js($array,$show_keys)
<
$dimensoes = array();
$valores = array();
Made this function to delete elements in an array;
?>
but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:
?>
Fast, compliant and functional 😉
//Creating a multidimensional array
/* 2. Works ini PHP >= 5.4.0 */
var_dump ( foo ()[ ‘name’ ]);
/*
When i run second method on PHP 5.3.8 i will be show error message «PHP Fatal error: Can’t use method return value in write context»
array_mask($_REQUEST, array(‘name’, ’email’));