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
Related
While retrieving values from array without index in PHP I am getting nothing.
From my database value is stored like ["SCHOOL"] and I want to get just SCHOOL from this.
It's not treated as array instead it's treated as a string.
What will be the solution if want to treat this as array and get value of that array.
My Code is as follows :
$stream_arr = $res_tbl['streams'];
which gives result as ["SCHOOL"]
and I want just SCHOOL from this.
I am using code as $stream = $stream_arr[0];
and I get '[' this as result.
If I assign manual value to $stream_arr = ["SCHOOL"],
above code works and returns SCHOOL as expected.
But for results from my database is not working where result is same as the one I manually assigned.
To eliminate braces from the string you can use below code.
$stream_arr = '["SCHOOL"]';
$temp=explode('"',$stream_arr);
$val=$temp[1];
echo $val; //it will dispaly 'SCHOOL'.
But check the insert query(from the place you store data into db) that why it is storing with braces? if it is done by you as required then proceed else first fix that issue instead of eliminating braces in php code.
I found what appears to be an abusable bug in the PHP language. When creating variable variables a seemingly illegal variable can be declared and then handled as long as you keep accessing it as a variable variable.
Example:
${'0'} = 1; //I am an illegal variable called $0
${'0'}++; //I can be accessed and manipulated.
var_dump(${'0'}); //Output: int(2)
This behavior appears rather odd. It is briefly mentioned in the official documentation for SimpleXml as a way to create variable names that contain hyphens but my example shows it can be abused pretty badly nonetheless.
I would like to know how come this behavior is possible and is tolerated when the code is parsed?
Internally PHP stores variables (zend_array* symbol_table) in a same data structure that is used for arrays. This allows you to have variable names with the same constraints as array keys.
Eg. Zend API function zend_set_local_var sets a value to symbol table using zend_hash_update, which is a function used to manipulate PHP array types as well.
We can't however allow every character in variable names in PHP source code. That's because lexical analysis must distinguish labels from other tokens. Variable variables offer a workaround for this.
It's not a bug nor a way to abuse anything. That being said, the documentation states that all labels, including variables, must have a regex form [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*, so i wouldn't rely on having arbitrary characters in variable names.
What ${'0'} = 1; actually does, it sets value 1 to the current scope's symbol table at key 0.
You can get that particular table with get_defined_vars function.
Looking at the source code, we'll see that the function just copies the current symbol table and returns it to caller.
PHP extract function (src) actually checks that keys have a valid label format (by calling php_valid_var_name), so you can't generate variables with funky names using that.
Anyway, even though it's possible to create variables of any name using variable variable syntax (even a variable with no name ${''}), i think it's bad practice. Even worse if a library expects or enforces you to do so. Saying it's a workaround might be a bit overstatement actually. Maybe it should be considered as an implementation detail and an undocumented feature.
#Nadav I don't have full idea about that but have a little bit idea,
Remember that curly braces({}) literally mean "evaluate what's inside the curly braces" so, you can squeeze the variable creation like you did ${'0'} = 1
reffered it from this http://php.net/manual/en/language.variables.php#73373
PHP stores variable in the array form, if you want to check then use $GLOBALS(an array) is the super global variable which has all the reference of the variables present in the script, it stores variable name as key and value as variable value, suppose below case:
<?php
${'0'} = 1; // here php stores it as 0th index in the array
${'1'} = 2; // here php stores it as 1th index in the array
$b = "I am b"; // here php stores it as bth index in the array
echo "<pre>";
print_r($GLOBALS);
output:
Array
(
[_GET] => Array
(
)
[_POST] => Array
(
)
[_COOKIE] => Array
(
)
[_FILES] => Array
(
)
[GLOBALS] => Array
*RECURSION*
[0] => 1
[1] => 2
[b] => I am b
)
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"];
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-->
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.