PHP array keys in a constant
I have a hopefully quick question. I have placed an array in a constant but when I add array keys it craps out. My code below.
<?php define("my_const_arr", serialize(a开发者_开发问答rray("page_ids" => array("1234", "4123")))); ?>
<?php $page_id = "4123"; ?>
<?php if(in_array($page_id, unserialize(my_const_arr["page_ids"]))): ?>
<h1>Hello Stackoverflow</h1>
<?php endif; ?>
You can't do my_const_arr["page_ids"]
at that point because it's still a string. You should unserialize it first and then access it
$arr = unserialize(my_const_arr);
if(in_array($page_id, $arr["page_ids"])):
You're using both unserialize and PHP mildly wrong:
<?php
define("my_const_arr", serialize(array("page_ids" => array("1234", "4123"))));
$page_id = "4123";
$a=unserialize(my_const_arr); // you need to usnerialize it before you can search for a specific key
if(in_array($page_id, $a["page_ids"])): ?>
<h1>Hello Stackoverflow</h1>
<?php endif; ?>
I would also like to point out that constants aren't particularly useful in an application you can control. Especially if that code is very relevant to your app.
<?php
$_myConstArr=array("page_ids" => array("1234", "4123"));
$page_id = "4123";
if(in_array($page_id, $_myConstArr["page_ids"])): ?>
<h1>Hello Stackoverflow</h1>
<?php endif; ?>
You will not get much overhead by doing this. I'd think that calling serialize/unserialize often would give you unwanted processing.
Post your exact scenario and a better solution might be made available.
<?php $arr = unserialize(my_const_arr) ?>
<?php if(in_array($page_id, $arr["page_ids"])): ?>
Change it that way
'my_const_arr' is a constant, not an array.
So,my_const_arr["page_ids"]
is incorrect.
Maybe you can try this:
$my_const_arr = unserialize(my_const_arr);
echo if(in_array($page_id,$my_const_arr)) 'HELLO STACKOVERFLOW' : '';
If there's no real need for the string-conversion, why not use a simple class as a container for constant values, like: EDIT: Sorry, just to leave a working approach:
Class MyConstants {
public static $PAGE_IDS = array(1234, 4123);
}
Outside you can access it like
if (in_array( 4123, MyConstants::$PAGE_IDS )) {
echo "got you! <br/>\n";
}
精彩评论