Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to define a constant array in PHP? [duplicate]

Tags:

php

Is there a way to define a constant array in PHP?

like image 786
trrrrrrm Avatar asked Feb 11 '10 01:02

trrrrrrm


People also ask

Can I define array in constant PHP?

PHP Constant Arrays In PHP7, you can create an Array constant using the define() function.

Can we define array as constant?

Arrays are Not Constants It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

What is a correct way of defining constants in PHP?

PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways: Using define() function. Using const keyword.

What are the ways to define a constant in PHP with example?

A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined. To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name.


2 Answers

define('SOMEARRAY', serialize(array(1,2,3)));

$is_in_array = in_array($x, unserialize(SOMEARRAY));

That's the closest to an array constant.

like image 190
useless Avatar answered Sep 21 '22 02:09

useless


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.

like image 41
Pekka Avatar answered Sep 23 '22 02:09

Pekka