How to create an empty array in PHP with predefined size?
I am creating a new array in a for loop.
PHP keeps complaining about the offset since for each iteration I add a new index for the array, which is kind of stupid.
Is there some way to predefine the number items in the array so that PHP will not show this notice?
In other words, can I predefine the size of the array in a similar way to this?
7 Answers 7
There is no way to create an array of a predefined size without also supplying values for the elements of that array.
The first zero in array_fill just indicates the index from where the array needs to be filled with the value.
You can’t predefine a size of an array in php. A good way to acheive your goal is the following:
Note that it is way faster to use array_fill() to fill an Array :
Possibly related, if you want to initialize and fill an array with a range of values, use PHP’s (wait for it. ) range function:
PHP Arrays don’t need to be declared with a size.
An array in PHP is actually an ordered map
You also shouldn’t get a warning/notice using code like the example you have shown. The common Notice people get is «Undefined offset» when reading from an array.
So that you can avoid the repeated code.
If you want to specify an array with a size for performance reasons, look at:
Best way to initialize (empty) array in PHP
In certain other languages (AS3 for example), it has been noted that initializing a new array is faster if done like this var foo = [] rather than var foo = new Array() for reasons of object creation and instantiation. I wonder whether there are any equivalences in PHP?
8 Answers 8
Creates empty array.
You can push values onto the array later, like so:
You actually have to use the unset() function to remove items:
. would remove «house» from the array (arrays are zero-based).
. would destroy the entire array.
To be clear, the empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically, rather than YOU assigning the indexes. Under the covers, PHP is actually doing this:
You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others. If you do that, PHP will fill in the missing index numbers, incrementing from the largest index number assigned as it goes.
. the item «dog» will be given an index number of 21. PHP does not do intelligent pattern matching for incremental index assignment, so it won’t know that you might have wanted it to assign an index of 30 to «dog». You can use other functions to specify the increment pattern for an array. I won’t go into that here, but its all in the PHP docs.
In ECMAScript implementations (for instance, ActionScript or JavaScript), Array() is a constructor function and [] is part of the array literal grammar. Both are optimized and executed in completely different ways, with the literal grammar not being dogged by the overhead of calling a function.
PHP, on the other hand, has language constructs that may look like functions but aren’t treated as such. Even with PHP 5.4, which supports [] as an alternative, there is no difference in overhead because, as far as the compiler/parser is concerned, they are completely synonymous.
If you need to support older versions of PHP, use the former syntax. There’s also an argument for readability but, being a long-time JS developer, the latter seems rather natural to me. I actually made the mistake of trying to initialise arrays using [] when I was first learning PHP.
This change to the language was originally proposed and rejected due to a majority vote against by core developers with the following reason:
This patch will not be accepted because slight majority of the core developers voted against. Though if you take a accumulated mean between core developers and userland votes seems to show the opposite it would be irresponsible to submit a patch witch is not supported or maintained in the long run.
However, it appears there was a change of heart leading up to 5.4, perhaps influenced by the implementations of support for popular databases like MongoDB (which use ECMAScript syntax).
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 can I implode an array while skipping empty array items?
Perl’s join() ignores (skips) empty array values; PHP’s implode() does not appear to.
Suppose I have an array:
instead of (IMHO the preferable):
Any other built-ins with the behaviour I’m looking for? Or is it going to be a custom jobbie?
9 Answers 9
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
Obviously this will not work if you have 0 (or any other value that evaluates to false ) in your array and you want to keep it. But then you can provide your own callback function.
I suppose you can’t consider it built in (because the function is running with a user defined function), but you could always use array_filter.
Something like:
How you should implement you filter only depends on what you see as «empty».
Based on what I can find, I’d say chances are, there isn’t really any way to use a PHP built in for that. But you could probably do something along the lines of this:
array_fileter() seems to be the accepted way here, and is probably still the most robust answer tbh.
How to define an empty object in PHP
with a new array I do this:
Is there a similar syntax for an object
17 Answers 17
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.
When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
The standard way to create an «empty» object is:
But I personally prefer to use:
It’s shorter and I personally consider it clearer because stdClass could be misleading to novice programmers (i.e. «Hey, I want an object, not a class!». ).
See the PHP manual (here):
stdClass: Created by typecasting to object.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
and here (starting with PHP 7.3.0, var_export() exports an object casting an array with (object) ):
However remember that empty($oVal) returns false, as @PaulP said:
Objects with no properties are no longer considered empty.
Regarding your example, if you write:
PHP key1 (an object itself)
Warning: Creating default object from empty value
PHP >= 8 creates the following Error:
Fatal error: Uncaught Error: Undefined constant «key1»
In my opinion your best option is:
I want to point out that in PHP there is no such thing like empty object in sense:
On other hand empty array mean empty in both cases
Quote from changelog function empty
Objects with no properties are no longer considered empty.
Short answer
Long answer
I love how easy is to create objects of anonymous type in JavaScript:
So I always try to write this kind of objects in PHP like javascript does:
But as this is basically an array you can’t do things like assign anonymous functions to a property like js does:
Well, you can do it, but IMO isn’t practical / clean:
Also, using this synthax you can find some funny surprises, but works fine for most cases.
php.net said it is best:
In addition to zombat’s answer if you keep forgetting stdClass
You can use new stdClass() (which is recommended):
Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:
Or you can convert the null value to an object which produces a new empty instance of the stdClass built-in class:
Use a generic object and map key value pairs to it.
Or cast an array into an object
to access data in a stdClass in similar fashion you do with an asociative array just use the <$var>syntax.
As others have pointed out, you can use stdClass. However I think it is cleaner without the (), like so:
However based on the question, it seems like what you really want is to be able to add properties to an object on the fly. You don’t need to use stdClass for that, although you can. Really you can use any class. Just create an object instance of any class and start setting properties. I like to create my own class whose name is simply o with some basic extended functionality that I like to use in these cases and is nice for extending from other classes. Basically it is my own base object class. I also like to have a function simply named o(). Like so:
This is a great start for a base «language» to build other language layers upon with the top layer being written in full internal DSLs. This is similar to the lisp style of development, and PHP supports it way better than most people realize. I realize this is a bit of a tangent for the question, but the question touches on what I think is the base for fully utilizing the power of PHP.







