Smarty echo of array variable with "-" in its name - php

I have variable that in PHP controller looks like
$data['content']['mods']['HTML-FORM-END']['html']
It is passed nicely in smarty, but when I try to show it any of these ways, it shows either 0 (assumes minus as operator and does some math), or says "unrecognized tag"
{$data.content.mods.HTML-FORM-BEGIN.html}
{$data.content.mods['HTML-FORM-BEGIN']['html']}
{$data.content.mods.HTML-FORM-BEGIN.html}
{$data.content.mods.HTML-FORM-BEGIN.html}
How can i print it without renaming array key in controller?

Your example references 'HTML-FORM-END' in your controller but 'HTML-FORM-BEGIN' in your view but I'll assume that isn't your issue and both exist. How about this?
{$data[content][mods][HTML-FORM-BEGIN][html]}
From what I can find it appears that the only way to get down into a multi-dimensional array in Smarty is with loops. Perhaps instead you could split your array into assigns in your controller to provide easy access:
foreach($data['content']['mods'] as $key => $values) {
$smarty->assign('content_mods_' . $key, $values['html'];
}
and then you could reference them in your template like this:
{$content_mods_HTML-FORM-BEGIN}
{$content_mods_HTML-FORM-END}
// etc.

Related

index of array with smarty variables is not working

I have created array variable in .php file
like
$arImagePath[TE] = 'XYZ';
in my .tpl
{$carnumber} is giving 'T' and {$carinitial} is giving 'E'.
I am trying to get value 'XYZ' as follows
{$arImagePath[{$carnumber}+{$carinitial}]}
I tried many combination still unavailable to get array value.
smarty version -2.6.26
Hoping for any help.
From documentation (Smarty v2) :
{$foo[bar]} <-- syntax only valid in a section loop, see {section}
So, if you want to access the array variable directly and you are not in a loop, you have to do it this way:
{$foo.bar} <-- display the "bar" key value of an array, similar to
PHP $foo['bar']
Now, to archive what you need:
// This assignment could change dynamically
{assing var="carnumber" value="T"}
{assing var="carinitial" value="E"}
// For the sake of clarity, I'm going to concat in one variable the above assignments
{assing var="index" value=$carnumber|cat:$carinitial}
//Now access the array at the index we need
{$arImagePath.$index} // XYZ

php: accessing array dynamically using a string variable

Its like this
I have a variable that has an array index in it, for e.g.
$var = 'testVar["abc"][0]';
or
$var = 'testVar["xyz"][0]["abc"]';
or it could be anything at run time.
Now when I try to access this by using this php code:
echo $$var;
or
echo ${$var};
I get a warning saying Illegal offset at line ...
but if I use this code, it works
eval('echo $'.$var);
I do not want to use eval(). Is there any other way?
EDIT:
The variable $testVar is an array build up on runtime and it could have multi-dimensional array built dynamically. Its format is not fixed and only the script knows by the use of certain variables that what the array could be.
for e.g. at any point, the array might have an index $["xyz"][0]["abc"] which I want to access dynamically.
My php version is 5.1
According to the documentation, what you are trying to accomplish is not possible:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
In your case, $$var tries to read a variable with the name testVar["xyz"][0]["abc"], and not indexing an array. You could dereference that array like this:
$a = "testVar";
echo ${$a}["xyz"][0]["abc"];

How to cast a value as integer in Smarty

Im having a little trouble in referencing indexes in arrays in Smarty. I believe that it is because the variable I am using as the index is a string. How may I cast this string as a integer within the template?
Thanks.
If I correctly understand the question, {$variable|intval}
The documentation shows many usage examples, especially with regards to accessing array elements.
{$foo} <-- displaying a simple variable (non array/object)
{$foo[4]} <-- display the 5th element of a zero-indexed array
{$foo.bar} <-- display the "bar" key value of an array, similar to PHP $foo['bar']
{$foo.$bar} <-- display variable key value of an array, similar to PHP $foo[$bar]
{$foo[bar]} <-- syntax only valid in a section loop, see {section}
I believe that it is because the
variable I am using as the index is a
string
I don't agree with that belief:
$arr = array('a');
$i = '0';
echo $arr[$i]; // echos a
I think the problem lies elsewhere. If you have further questions, you should include some of your code.
If it's already assigned to a variable, say $var, you can set the type of a variable like this:
{$converted = settype ($var, 'integer')}
You don't have to use the $converted value, but if you don't assign it, the bool will show up in your page.
since i am not allowed to comment (doh), i will just say that #webbiedave code is correct in php, but in smarty it doesnt work. i have just spent too much time trying to figure it out why i am not accessing data from array in template, and i found out that i had array with integer keys and the parameter which i used for key in smarty was string, so it wasnt working as expected. i solved it like that:
<!--{debug says}
{$item}=> Array (2)
name=> "lalala"
id => "123"
...
{$arrays} => Array (7)
123=> Array (3)
other_part_i_care=> "bebebe"
...
-->
{$arrays[$item.id].other_part_i_care} <!--this doesnt return anything-->
{assign var='item_id' value=$item.id} <!--my guess here it gets interpreted as int -->
{$arrays[$item_id].other_part_i_care} <!--this return expected outcome-->

Help loading contstants stored in serialized array using eval() and constant()

DISCLAIMER:
Please read carefully as this is NOT a question about storing arrays in constants or simple eval() or serialize() techniques. This IS a question primarily about how constants work in PHP and why the constant() function is not working to convert a constant name into a constant value. Thanks.
BACKGROUND:
For various reasons, I started out with a flat config file for a homebrewed LAMP(PHP) CMS (in private development). Looking back this may have been misguided, and I have transitioned my variable storage into a DB table. However, the bulk of the code still depends on the CONSTs, so I use eval("define(A, B...);") to load the DB values A and B into constants. This part works fine. But it gets a bit more complicated.
PROBLEM:
The problem I'm having now is with constants in arrays (NB. NOT arrays in constants). I have a big, GLOBAL array called defaults that contains config settings in the format shown below.
Initially, I declare: <?php define('THIS_IS_A_CONSTANT', 'abcdefg'); ?> (And THIS WORKS...)
Next, I define $GLOBALS['defaults'] as the following nested array:
Array
(
'var_name' => Array
(
'display' => THIS_IS_A_CONSTANT,
'value' => 12,
'type' => 'int',
'params' => Array ( ... )
),
...
Lots more variables...
...
)
To prevent the client (who has file system access but no direct DB access but can change certain values, including most constants, via the CMS's administrative backend) from mucking up this array structure, I serialize the array structure and store that string in the DB. On each page request, I first define all the constants (stored in the DB) using the eval(define(A,B...)), then I unserialize the array above (which was serialized and stored in the DB). However, no matter what I try I cannot get the values at $GLOBALS['defaults']['var_name']['display'] to be recognized as the values that the constants contain. Instead, the constant name shows up and NOT the constant value (in other words, my output contains THIS_IS_A_CONSTANT instead of 'abcdefg'). Very frustrating, right?
I've tried something like the following (where $arr contains the unserialized array that I fetch from the DB):
foreach ($arr as $item => $contents) {
$display = isset($contents['display']) ? $contents['display'] : 1;
$value = constant("$display");
// This doesn't work, though it seems like it should
$contents['display'] = $value;
// Neither does this, no matter how much I juggle the quotation marks and backslashes
eval("\$contents['display'] = constant(\"$value\");");
// or this ...
eval("\$contents['display'] = $value;");
// or this ...
eval("\$contents['display'] = \$value;");
// or a number of other things...
}
$GLOBALS['defaults'] = $arr;
QUESTIONS:
Has anyone dealt with this kind of situation before? Can anyone advise me how to force my constants to be recognized as CONSTANTS and not strings. Do I need to serialize my array differently? Or maybe process the unserialized array differently (after retrieving it from the DB)? Is these some combination of eval() and constant() that will allow me to do this? Why are the constants within my array behaving badly while the constants I define normally are working without problem? Any help at all would be greatly appreciated, as I've been puzzling over this for a few days now and haven't come to any solutions.
All the best, Dakota.
Although eval does have its uses, this is not one of those cases. You have no idea what is being submitted to the eval at run time - and by the sounds of things you are storing something which you are then treating as code in a user-data storage location.
If the constant was defined before the array was declared then the serialized version would contain the value instead of the label. I can only assume that the value may differ depending on the context at run-time.
I would suggest that a better solution would be to roll your own macro language in PHP, e.g. something like:
<?php
global $defs;
$defs=array(
'THIS_IS_A_CONSTANT' => 'abcdefg',
'SO_IS_THIS' => 23
);
// for inline constants
foreach ($defs as $label =>$val) {
define($label, $key);
}
replacer($defs,true);
function replacer($in, $init=false;)
{
static $defs;
static $vals;
if ($init) {
$defs=array_keys($in);
$vals=array_values($in);
return count($in);
}
return str_replace($defs, $vals, $in);
// you might want to use preg_replace() with a pattern based on $defs for a neater solution
}
function fix_var(&$in)
{
if (is_array($in)) {
foreach ($in as $key=>$dummy) {
fix_var($in[$key]);
}
} else {
$in=replacer($in);
}
}
?>
C.
First, why are you evaling? From what you are saying you want the value of $GLOBALS['defaults']['var_name']['display'] to be the value of the constant THIS_IS_A_CONSTANT. You have de-serialized the string from your database and shoved in in $GLOBALS['defaults'] and the string stored the value as the constant name, not the value of the constant.
Have you tried:
<?php
define('THIS_IS_A_CONSTANT', 'abcdefg');
$value = constant($GLOBALS['defaults']['var_name']['display']);
//$value should now be abcdefg not THIS_IS_A_CONSTANT
$GLOBALS['defaults']['var_name']['display'] = $value;
?>
If "$GLOBALS['defaults']['var_name']['display']" does contain the string THIS_IS_A_CONSTANT then all you should need to do is pass that string to the constant funct.
Am I missing something?

in php is there a way to dump "all" variable names with their corresponding value?

if the title seems too vague..
uhm i wanted to display every variable that i used to generate a page along with their variable names and values, is it possible and how?
foreach($_SESSION as $varname => $value) {
print "<b>".$varname."</b> = $value <br/>";
}
^the above sample is what i use to display all session variables, what if i need to display the variables i set to display the page? are they registered also in some form of an array or should i also echo them individually?
You can use get_defined_vars() which will give you an array of all variables declared in the scope that the function is called including globals like $_SESSION and $_GET. I would suggest printing it like so:
echo '<pre>' . print_r(get_defined_vars(), true) . '</pre>';
The easiest way to do this is with get_defined_vars().
From the Documentation
This function returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.
Producing a var_dump of this array will provide you with an extensive list.
var_dump( get_defined_vars() );
A couple other interesting functions in the same area are get_defined_constants() and get_included_files()...

Categories