I'd like to make a language switcher, but the default options don't work for me, so I'd like to use the 'raw' attribute. I'm currently just testing whether my languages will show up at all:
$translations = pll_the_languages(array('raw'=>1));
echo $translations[0]['name'];
This code doesn't output anything, but doesn't crash the website either. What am I missing?
you would need to get it like this:
echo $translations['nl']['name'];
It's better to verify if the key exists in the array or not.
$value= "";
if($key_exists('nl',$translations) && $key_exists('name',$translations['nl'])){
$value = $translations['nl']['name'];
}
echo $value;
$translations = pll_the_languages(array('raw'=>1));
echo $translations[nl][name];
I thought the second array would be named after the 'order' number of the language, turns out it was the slug. Thanks to Danyal for helping me find the array's framework.
Related
I'm still learning PHP, but I needed a way of keeping track of a list of two associated values, a cinema and its postcode. Now before you read any further I must stress that I do not technically need this problem solving as I have since replaced it with a more efficient method. I'm really just wanting to know why it doesn't work as I can't find anything about it elsewhere.
$cinema_locations = array(
array("Odeon", "M4 2BS"),
array("Cineworld", "OL7 0PG"),
array("Vue", "M50 3AG"),
array("AMC", "M3 4EN")
);
for ($i=0; $i<count($cinema_locations); $i++) {
if ($cinema_locations[$i][0] == $_GET['cinema_name']) {
$postcode = $cinema_locations[$i][1];
return;
}
}
As you can probably tell from the code, I am trying to loop through the main array so that I may compare the first value of each child array against a $_GET variable. I have checked over this code multiple times and even showed some of my other coder friends and none of us can find anything wrong, syntax or otherwise. And yet, the browser shows only a white screen. If anyone can shed some light on the issue, I and my friends would be most appreciative; and who knows, it may help someone else with the same issue.
For anyone that may be curious, I replaced the 2D array with an associative array thus:
$cinema_locations = array(
"Odeon" => "M4 2BS",
"Cineworld" => "OL7 0PG",
"Vue" => "M50 3AG",
"AMC" => "M3 4EN"
);
$postcode = $cinema_locations[$_GET['cinema_name']];
EDIT
Thanks rishi, that did it. I never even considered that the return would nullify the result. Using break stopped the loop and the rest of the page loaded fine.
May be you should write break; instead of return;
You needed to break your for loop if you meet the condition. and continue with the below code.
return will instantly returns value from where its called.
For situations in which you cannot change the array structure, this code is a better approach.
// same array as the original post
$cinema_locations = array(
array("Odeon", "M4 2BS"),
array("Cineworld", "OL7 0PG"),
array("Vue", "M50 3AG"),
array("AMC", "M3 4EN")
);
foreach ($cinema_locations as $c_loc) {
$postcode = ($_GET'cinema_name'] == $c_loc[0]) ? $c_loc[1] : null;
}
print $postcode;
Of course, you should never use $_GET directly like this, but you probably already knew that.
I want to know how can I concatenate [und][0][value].
I don't want to write every time [und][0][value]. So I have do like this:
<?php
$und_value = $load->field_testimonial_location['und'][0]['value'];
$query = db_select('node','n');
$query->fields('n',array('nid'));
$query->condition('n.type','testimonial','=');
$result = $testimonial_query->execute();
while($fetch = $result->fetchObject()){
$load = node_load($fetch->nid);
// $location = $load->field_testimonial_location['und'][0]['value'];
$location = $load->field_testimonial_location.$und_value;
echo $location;
}
But its not working. It outputs Array Array So have any idia for this problem? How can I do? Full code here
Why don't you make some function which will take node field as parameter and return it's value
function field_value($field){
return $field['und'][0]['value'];
}
Something like that (not tested).
But if you don't want to use function try using curly braces like:
$location = $load->{field_testimonial_location.$und_value};
That should work...
Extending answer posted by MilanG, to make function more generic
function field_value($field, $index = 0 ){
return $field['und'][$index]['value'];
}
There are time when you have multi value fields, in that case you have to pass index of the value also. For example
$field['und'][3]['value'];
Please do not use such abbreviations, they will not suit all cases and eventually break your code.
Instead, there is already a tool do create custom code with easier syntax: Entity Metadata Wrapper.
Basically, instead of
$node = node_load($nid);
$field_value = $node->field_name['und'][0]['value'];
you can then do something like
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node);
$field_value = $node_wrapper->field_name->value();
With the node wrapper you can also set values of a node, it's way easier and even works in multilingual environments, no need to get the language first ($node->language) or use constants (LANGUAGE_NONE).
In my custom module, I often use $node for the node object and $enode for the wrapper object. It's equally short and still know which object I am working on.
I have a variable that gets the language from the URL (either jp or en)
$lang = $_GET["lang"];
And for each language I have a row in the database
$menu_name_jp=$row['menu_name_jp'];
$menu_name_en=$row['menu_name_en'];
How can I combine the $lang variable with the $menu_name_ variable so I get a different variable according to the $lang
I have tried something like that but it doesn't work (of course :))
$menu_name="$menu_name_$lang";
MORE INFORMATION
I have tested the examples but id didnt work as because I also have a variable called just $menu_name with no lang in the end which serves for the default language. And what I am doing is that:
if ($lang=="df")
{
$menu_name=$menu_name;
}
else
{
$menu_name=$menu_name.'_'.$lang;
}
So, the result is that it just append the default menu_name with the lang. Like this
HOME_jp
Thanks
Doesn't get any simpler than this:
$menu_name = $row['menu_name_' . $lang];
You can use,
echo $menu_name = ${'menu_name_'.$lang };
But rather I will suggest you to create an array such as,
$menu_name = array("jp" => $row['menu_name_jp'],"en" => $row['menu_name_en']);
echo $menu_name[$lang];
DEMO.
You have to append the values using dot operator. Try with
$menu_name="menu_name_".$lang;
${"menu_name_".$lang} = $row['menu_name_'.$lang'];
Then you can call it like this: echo $menu_name_jp
That's what you need:
<?php
$menu_name_jp='one';
$menu_name_en='two';
$lang = 'jp';
echo ${'menu_name_'.$lang};
I have $config variable that have arrays inside it. In smarty I assign the variable like this:
$smarty->assign('config', $config);
when I call it, I used this : {$config.wateverarrayyouwant}
now I want to do the same thing with php. I want to define them in the same manner. How can I define all the arrays in $config in just one line?
I only know how to define a variable one at a time by using this :
define('wateverarrayyouwant', $config['wateverarrayyouwant']);
I tried changing wateverarrayyouwant to a variable because it can be any array :
define('$wateverarrayyouwant', $config[$wateverarrayyouwant]);
but the code above does not work. what is a good way to achieve what I want?
If you want to create a define for each key value pair in the array you can use:
<?php
foreach($config as $key => $value) {
define($key, $value);
}
I will note however that you cannot define array values, all define's must be scalar:
The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values.
If you check the OP's answer for further explanation of what he's trying to achieve, it can be done with:
<?php
foreach($config as $key => $value){
$$key = $value;
}
?>
This question cannot be done. because I am trying to define a variable as a constant. I was just thinking about how can I reduce the letters for variables and never though that I better leave them alone. Logically, why do somebody need to change $config[$wateverarrayyouwant] to wateverarrayyouwant. I was only thinking about maintaining a neat code. but now I am thinking about it.. it is better to leave it as it is : $config[$wateverarrayyouwant]
This can be done with:
foreach($config as $key => $value){
$$key = $value;
}
You may not even want to use define here. define is used to create constants not plain variables and that carries with it certain connotations:
they are immutable for the life of the script
they must be scalar
If you just want an array variable then define it like normal with:
$whatever = array(
'key1' => 'value1'
);
I want to create 1 variable name, but part of the name is the value stored in $i. Same for the GET result:
$Site.$i = $_GET['site'.$i]; // Should look something like $Site1 = $GET['site1'];
Please help me understand how to do this.
If you want a set of related variables, use an array:
$site[ $i ] = $_GET['site'.$i];
Even better, your GET parameters can also be an array
HTML
<input name="site[foo]" value="bar" />
PHP
$site = $_GET[ "site" ];
print_r( $site );
output
$site = array(
"foo" => "bar"
)
If you want the indexes for the array to decided automatically then you can do
<input name="site[]" value="foo" />
<input name="site[]" value="bar" />
<input name="site[]" value="baz" />
and get $_GET[ "site" ] out as
$site = array(
0 => "foo",
1 => "bar",
2 => "baz"
);
Direct Answer to Question
This is how you can do it. Not the best idea however.
$var = "$Site$i";
$$var = $_GET['site'.$i];
This makes use of variable variables.
Alternative Maintaining Current URL Structure
Alternatively perhaps something like this might work for you:
$vars = array();
foreach($_GET as $key => $value) {
if(0 === strpos($key, 'site')) { // Only grab value if the key is prefaced by the string 'site'
// You must sanitise the value some way here eg:
// $value = filter_var($value, FILTER_SANITIZE_STRING);
$vars[] = $value;
}
}
See filter_var() man page for more information on PHP filters and sanitisation/validation.
Revised URL Structure
I think this probably best solved however by making use of HTML arrays at the point your URL is generated. For more information on HTML arrays please see the PHP man page.
This allows you to access your information like the following:
$site1 = $_GET['site'][0];
$site2 = $_GET['site'][4];
This is the most logical method of dealing with this situation.
Update also see #Mat's answer for more information on this.
This is a bad idea for several reasons:
You have to loop through $_GET to find all variables (there's no language construct to pattern-match them)
Dynamic variables names are confusing, and may open security holes.
You will find that using an array will solve the second point, and also make it a lot easier to work with the code.
The first point can be solved by only using variable names you know. Send a variable containing a count how how many "sites" there are, for example:
site1=example&site2=example2&sitecount=2
This way you know that you only need to read site1 and site2, and you donät need to examine any other GET variables.
you van use $ as $_GLOBAL like this.
${'Site' . $i} = $_GET['site' . $i];
or you can use extract
please read the warnings about exract.
You can use variable variables like this:
$varname = $Site.$i;
$$varname = $_GET['site'.$i];
Doing this is discouraged however, because this is a huge security risk. You may write classes with fields representing your values from $_GET and validating them within the class.