PHP Constants Containing Arrays?
NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.
You can also serialize your array and then put it into the constant:
# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));
# use it
$my_fruits = unserialize (FRUITS);
PHP constant as an array
What you are looking for is called Constant array :
it is now possible to do this with define() but only for PHP7
. However you can do this on PHP5.6 by using the const keyword and it is not possible to perform this in lower PHP versions
here is an example :
<?php
define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"
define('MYCONST', [
'key' => "value"
]);
echo MYCONST['key']; // outputs "value"
Is It Possible to Declare Constant with Associative Array
The code you posted doesn't work on PHP 5.
Declaring constant arrays using define
is a new feature introduced in PHP 7.0.
Since PHP 5.6 it is possible to define a constant array using the const
keyword:
const OUR_OFFICE = [
"Japan" => "Tokyo Shibuya Office",
"Taiwan" => "Taipei Shilin Office",
"Korea" => "Seoul Yongsan Office",
"Singapore" => "Singapore Novena Office",
"Australia" => "Sydney Darlinghurst Office",
];
The documentation highlights the differences between define()
and const
:
As opposed to defining constants using
define()
, constants defined using theconst
keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements ortry
/catch
blocks.
Is there a way to define a constant array in PHP?
No, it's not possible. From the manual: Constants Syntax
Only scalar data (boolean, integer, float and string) can be contained in constants. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.
If you need to set a defined set of constants, consider creating a class and filling it with class constants. A slightly modified example from the manual:
class MyClass
{
const constant1 = 'constant value';
const constant2 = 'constant value';
const constant3 = 'constant value';
function showConstant1() {
echo self::constant1 . "\n";
}
}
echo MyClass::constant3;
Also check out the link GhostDog posted, it's a nice workaround.
Is it possible to declare an array as constant
UPDATE: this is possible in PHP 7 (reference)
// Works as of PHP 7
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
ORIGINAL ANSWER
From php.net...
The value of the constant; only scalar and null values are
allowed. Scalar values are integer, float, string or boolean values.
It is possible to define resource constants, however it is not
recommended and may cause unpredictable behavior.
$months = array("January,"February",...)
will be just fine.
php const arrays
Your code is fine - arrays cannot be declared constant in PHP before version 5.6, so the static approach is probably the best way to go. You should consider marking this variable as constant via a comment:
/** @const */
private static $myArray = array(...);
With PHP 5.6.0 or newer, you can declare arrays constant:
const myArray = array(...);
Where to put arrays with constant value that will be accessed many times?
TL;DR: Use a class constant for maximum performance (see at the end of the answer).
Let's look at the performance characteristics of the different versions (and why):
PHP 5
Arrays in static properties are created at compile time, very quickly, without involvement of the VM. Accessing static properties though is a bit slower than accessing normal variables, but still much faster than recreating the array on every run.
Arrays in normal functions get re-created at run-time with every run, in any case. And creation at run-time in VM means that every element is added one-by-one, in individual opcodes, which means quite a bit of overhead (especially if the array is larger than just 1-2 elements).
PHP 7.0
Arrays in normal functions [in general] are created a bit faster due to array creation in general being sped up (optimizations in HashTable handling). If it's all constant values, it's cached in the internal constant values array, but duplicated upon each access. However doing a direct highly specialized copying action is obviously faster than adding elements one-by-one to the array like in PHP 5.
Opcache is marking them as IMMUTABLE internally, which allows direct access [so you get full speed with opcache]. (See also https://blog.blackfire.io/php-7-performance-improvements-immutable-arrays.html)
PHP 7.1
Arrays are natively always cached in the internal constant values array, with copy-on-write semantics.
Now using a static property is slower as looking up a static property is less performant than a simple write to a variable. [Direct access to a variable has no extra overhead.]
Also note that since PHP 5.6 you can declare (class) constants with the value of an array. PHP 7.1 allows direct substitution of class constants of the same class and will add the array directly to the internal constant values array for direct usage with in_array.
I.e. the fastest code is (with 7.1 at least):
private const Ms = array(82, 83, 84, 104, 106, 107, 109, 140, 190);
private const Gs = array(0, 1, 20, 21, 28, 90, 91, 92);
private const Ts = array(0, 1);
...
...
public function checkFileGcodeFormat()
{
if (! ($this->hasM() && $this->hasNoXYZ() && in_array($this->M, self::Ms)) || ($this->hasG() && in_array($this->G, self::Gs)) || ($this->hasT() && $this->hasNoXYZ() && in_array($this->T, self::Ts)) )
return false;
else
return true;
}
how to use const array instead of const variable?
As my php version is old, this is why i have used this code
define('randomize_api' , serialize(array('AIzaSyBhl0bx7Psf5LKUhboBvtTTufSxXO1PO1s','AIzaSyD8rmarWEJyQwxMqNuFHLQ5E5tcgi4BD10')));
$avv = unserialize(randomize_api);
$bss = $avv[rand(0,count($avv)-1)];
define('randomize_value_api' , $bss );
and const apiKey
this inside class, i simply assign const apiKey = randomize_value_api;
i know long way,, it can be shorter but i used it for my convenient..
Related Topics
How to Remove All Non Printable Characters in a String
How to Add/Remove Pkcs7 Padding from an Aes Encrypted String
Show Values from a MySQL Database Table Inside a HTML Table on a Webpage
What Kind of String Is This? How to Unserialize This String
Is There Way to Use Two PHP Versions in Xampp
Where Do We Use the Object Operator "-≫" in PHP
How to Test a Url For 404 in PHP
Global or Singleton For Database Connection
Convert Backslash-Delimited String into an Associative Array
Issue Reading Http Request Body from a Json Post in PHP
What Are the Disadvantages of Using Persistent Connection in Pdo
PHP: Running Scheduled Jobs (Cron Jobs)
Correct File Permissions For Wordpress
How to Detect Search Engine Bots With PHP
Laravel: Syntax Error or Access Violation: 1055 Error
PHP Multidimensional Array Searching (Find Key by Specific Value)