php array item 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’);
How to add elements to an empty array in PHP?
If I define an array in PHP such as (I don’t define its size):
Do I simply add elements to it using the following?
9 Answers 9
Both array_push and the method you described will work.
It’s better to not use array_push and just use what you suggested. The functions just add overhead.
Based on my experience, solution which is fine(the best) when keys are not important:
You can use array_push. It adds the elements to the end of the array, like in a stack.
You could have also done it like this:
REMEMBER, this method overwrites first array, so use only when you are sure!
When one wants elements to be added with zero-based element indexing, I guess this will work as well:
Both array_push and the method you described will work.
Above is correct, but below one is for further understanding
Not the answer you’re looking for? Browse other questions tagged php arrays variables 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.
Insert new item in array on any position in PHP
How can I insert a new item into an array on any position, for example in the middle of array?
22 Answers 22
You may find this a little more intuitive. It only requires one function call to array_splice :
If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.
A function that can insert at both integer and string positions:
There is no native PHP function (that I am aware of) that can do exactly what you requested.
I’ve written 2 methods that I believe are fit for purpose:
While faster and probably more memory efficient, this is only really suitable where it is not necessary to maintain the keys of the array.
If you do need to maintain keys, the following would be more suitable;
This way you can insert arrays:
If you want to keep the keys of the initial array and also add an array that has keys, then use the function below:
Based on @Halil great answer, here is simple function how to insert new element after a specific key, while preserving integer keys:
This is what worked for me for the associative array:
This is also a working solution:
if unsure, then DONT USE THESE:
because with + original array will be overwritten. (see source)
Solution by jay.lee is perfect. In case you want to add item(s) to a multidimensional array, first add a single dimensional array and then replace it afterwards.
Adding an item in same format to this array will add all new array indexes as items instead of just item.
Note: Adding items directly to a multidimensional array with array_splice will add all its indexes as items instead of just that item.
Hint for adding an element at the beginning of an array:
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 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
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.
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.