2 strings in 1 where one of the strings is $row related - php

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};

Related

How to echo a language's name using the 'raw' attribute?

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.

How to concatenate variable in drupal

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.

Dynamically created Variables in PHP produce occasionally names like "_GET" or "_POST" instead of the variable names

I have a function from which I call many different variables, and produce another (dynamically created) return variable.
All good. (I explain my Problem below this PHP 5.3 example)
function showArrayIntersection($ar1, $ar2) {
$dynamicName = array_search($ar1, $GLOBALS) . '_' . array_search($ar2, $GLOBALS);
global ${$dynamicName};
${$dynamicName} = implode(array_values(array_intersect($ar1, $ar2)));
}
$Bankers = [6,7,0,6,5,6,2]; // `[]` is equivalent to `array()` introduced in PHP 5.4
$Bond = [6,7,0,5,0];
$Politicians = [4,6,1,6,4,6,3];
$James = [0,1,0,3,7];
showArrayIntersection($James, $Bond);
showArrayIntersection($Bankers, $Politicians);
echo "Moneysystem: $Bankers_Politicians\n";
echo "Moneypenny : $James_Bond\n";
Output:
Moneysystem: 666
Moneypenny : 007
This works most of the time well, but sometimes only instead of a variable name like $James_Bond I get a variable name like POST_POST or GET_GET, meaning instead of the name James or Bond PHP returns either a "_GET" or a "_POST".
Since AbraCadaver asked full of solicitousness: "What in the world are you doing?"
here my solution and explanation:
Einacio: I coudn't create the names on the fly because the already arrive from a first function dynamically, so the actual variable name is not the true name.
And AbraCadaver pointed out that array_search() does not accept an array; unfortunately for sake of brevity I omitted that I pass on as a first argument not an array but another dynamic created variable from the root - I didn't want to make it too complicated, but basically it works like this:
function processUsers ($userName , $request2send ){
global ${$user.'_'.$request2send};
$url2send = "http...?request=".$request2send ;
...
$returnedValue = receivedDataArray ();//example elvis ([0] => Presley );
${$user.'_'.$request2send} = $returnedValue;
}
--- now Now I get the value of the function in the root ---
$firstValue = processUsers ("cuteAnimal" , "getName");
// returns: $cuteAnimal_getName = "Mouse"
and
$secondValue = processUsers ("actorRourke" , "getFirstName");
// returns: $actorRourke_getFirstName = "Mickey";
And now the bummer - a second function which needs the first one to be completed:
function combineValues ($firstValue , $secondValue ){
global ${$firstValue.'AND'.$secondValue};
${$firstValue.'_'.$secondValue} = $firstValue." ".$secondValue;
}
// returnes $actorRourke_getFirstNameANDcuteAnimal_getName = "Mickey Mouse";
Of course the second function is much more complicated and requires first to be completed,
but I hope you can understand now that it is not an array directly which I passed on but dynamic variable names which I could not just use as "firstValue" but I needed the name "actorRourke_getFirstName".
So AbraCadaver's suggestion to use $GLOBALS[..] did not work for me since it requires arrays.
However: Thanks for all your help and I hope I could now explain the issue to you.
Argument 1 for array_search() does not accept an array.
print_r($GLOBALS); will show the empty $_GET and $_POST arrays.
What in the world are you doing?
To go with Einacio:
function showArrayIntersection($ar1, $ar2) {
$GLOBALS[$ar1 . '_' . $ar2] = implode(array_intersect($GLOBALS[$ar1], $GLOBALS[$ar2]));
}
showArrayIntersection('James', 'Bond');
echo "Moneypenny : $James_Bond\n";
You could check to make sure they exist of course isset().
how about just using the names of the variables? it would also avoid value conflicts
function showArrayIntersection($ar1, $ar2) {
$dynamicName = $ar1 . '_' . $ar2;
global ${$dynamicName};
${$dynamicName} = implode(array_values(array_intersect($_GLOBALS[$ar1], $_GLOBALS[$ar2])));
}
$Bankers = [6,7,0,6,5,6,2]; // `[]` is equivalent to `array()` introduced in PHP 5.4
$Bond = [6,7,0,5,0];
$Politicians = [4,6,1,6,4,6,3];
$James = [0,1,0,3,7];
showArrayIntersection('James', 'Bond');
showArrayIntersection('Bankers', 'Politicians');
echo "Moneysystem: $Bankers_Politicians\n";
echo "Moneypenny : $James_Bond\n";

Using array value with index as Variable Variable

The title may be a little confusing. This is my problem:
I know you can hold a variable name in another variable and then read the content of the first variable. This is what I mean:
$variable = "hello"
$variableholder = 'variable'
echo $$variableholder;
That would print: "hello". Now, I've got a problem with this:
$somearray = array("name"=>"hello");
$variableholder = "somearray['name']"; //or $variableholder = 'somearray[\'name\']';
echo $$variableholder;
That gives me a PHP error (it says $somearray['name'] is an undefined variable). Can you tell me if this is possible and I'm doing something wrong; or this if this is plain impossible, can you give me another solution to do something similar?
Thanks in advance.
For the moment, I could only think of something like this:
<?php
// literal are simple
$literal = "Hello";
$vv = "literal";
echo $$vv . "\n";
// prints "Hello"
// for containers it's not so simple anymore
$container = array("Hello" => "World");
$vv = "container";
$reniatnoc = $$vv;
echo $reniatnoc["Hello"] . "\n";
// prints "World"
?>
The problem here is that (quoting from php: access array value on the fly):
the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages.
Would PHP allow the subscript notation anywhere, one could write this more dense as
echo $$vv["Hello"]
Side note: I guess using variable variables isn't that sane to use in production.
How about this? (NOTE: variable variables are as bad as goto)
$variablename = 'array';
$key = 'index';
echo $$variablename[$key];

Need Help With PHP Function, It doesn't work when i pass value by variable

Here's a php function and it works perfectly.
$values = array(
'php' => 'php hypertext processor',
'other' => array(
'html' => 'hyper text markup language',
'css' => 'cascading style sheet',
'asp' => 'active server pages',
)
);
function show($id='php', $id2='') {
global $values;
if(!empty($id2)) {
$title = $values[$id][$id2];
}
else {
$title = $values[$id];
}
echo $title;
}
When i execute this <?php show(other,asp); ?> it displays active server pages and it works, but when i do it this way it shows an error
<?php
$lang = 'other,asp'
show ($lang);
?>
It doesn't work., Please help me out here
P.S : It works if i pass variable with single value (no commas)
If you'd like to pass it in the way you have it,
maybe try using explode:
function show($id='php') {
global $values;
$ids = explode(',',$id);
if(!empty($ids[1])) {
$title = $values[$ids[0]][$ids[1]];
}
else {
$title = $values[$ids[0]];
}
echo $title;
}
You can't pass two variables in one string. Your string $lang needs to be split up into two vairables:
$lang1 = 'other';
$lang2 = 'asp';
show($lang1, $lang2);
It fails because the key "other,asp" doesn't exist in $values.
In other words, it is trying to evaluate the following:
$title = $values['other,asp'];
PS, it's always useful to provide an actual error rather than saying "it doesn't work".
This is because $lang will get interpreted as a single argument, so $id2 will be 'other,asp'. You need to pass them into the function separately:
$id1 = 'other';
$id2 = 'asp';
show($id1,$id2);
P.S : It works if i pass variable with single value (no commas)
You are assigning $lang to the value 'other,asp', and then passing that sole $lang variable to the show function. There is no key named "other,asp" in your $values array.
Having a comma in the string doesn't mean you're splitting the parameters, it means you're passing a single string value. You have to "pass a variable with a single value", or do it like this for multiple parameter values:
$lang = "other";
$sub_lang = "asp";
show ($lang, $sub_lang);
You are returning one string instead of the two required... how about rewriting your function to handle them instead?

Categories