How to define an array element using a PHP variable - php

community.
I've been looking for an answer, but not close enough to this scenario
I have a code like this (actually working fine):
array('desc'=>'Home')
It is working defining it as text (Home) but I would rather to use it as a PHP variable due multilanguage site. Using the language package I have a variable such:
$lang['HOME'] = 'Home';
So depending on the language selected, the value changes
In other words, I need the array to have the variable value as the element
array('desc'=>'variablehere')
Can anyone plese let me know what am I missing? I have tried to set it as variable, as echo and so other ways.
Thanks a lot!

Like this?
$myArray = array('desc' => $variable);
or
$myArray = array(
'desc' => $desc,
'name' => $name
);
In your case:
$lang = array('HOME' => $homeVariable);

Use a multi-dimensional array. e.g., given something like
$lang = 'en';
$key = 'desc';
The exact array structure depends on your needs, but it could either be primarily by language, or by key-to-translate:
language-based:
$translations = array(
'en' => array('desc' => 'foo'),
'fr' => array('desc' => 'bar')
);
$text_to_display = $translations['en']['desc']; // produces 'foo'
or
$translations = array(
'desc' => array(
'en' => array('desc' => 'foo'),
'fr' => array('desc' => 'bar')
)
)
$text_to_display = $translations['desc']['fr']; // produces 'bar'

Use a translate function instead:
// It can be key-based, i.e., t('home_string'), or literal like below
t('Home');
function t($text, $language = NULL)
{
if (!$language) {
// determine visitor's language
}
// look up translation in db/file
// if none found just return $text as is
}

Related

Check if an array value exist

$city = $_GET['cityselect'];
add_query_arg( array ( 'city' => $city, 'key' => 'value' );
Basically i want to check if $city exists and if not i want to remove both key and value, ie 'city' => $city, (comma included). So the output would be:
add_query_arg( array ( 'key' => 'value' );
Any idea?
Only add the city key if it is set, like this:
$arg = array( 'key' => 'value');
if( isset( $_GET['cityselect']))
$arg['city'] = $_GET['cityselect'];
add_query_arg( $arg);
try this
$data = array();
if(isset($_GET["cityselect"])){
$data["city"] = $_GET["cityselect"];
}
add_query_arg($data); // ..
For the short but ugly one-liner version:
add_query_arg($args = (!empty($_GET['cityselect'])) ? array('city' => $_GET['cityselect'], 'key' => 'value') : array('key' => 'value');
Slightly more elegant:
if(!empty($_GET['cityselect']))
add_query_arg(array('city' => $_GET['cityselect'], 'key' => 'value'));
else
add_query_arg(array('key' => 'value'));
Have assumed use of empty, but substitute for isset if applicable to your circumstances.
If you're attempting to remove city if it doesn't exist, you could do:
$city = isset($_GET['cityselect']) ? $_GET['cityselect'] : null;
if (empty($city)) unset($yourArray['city']);
This assumes you already have an array, $yourArray, pre-defined with a city index.
I would recommend to only insert the city index after you've verified it though, such as:
if (isset($_GET['cityselect']) && !empty($_GET['cityselect'])) {
$yourArray['city'] = $_GET['cityselect'];
}
UPDATE: You could also use array_filter() to remove all indexes with missing values after you're done populating it:
$yourArray = array_filter($yourArray);
This will return an array with all empty values stripped; In your case, if city is empty it will be removed from the array.
You can use array_search() (Searches the array for a given value and returns the corresponding key if successful).

How do I make this little PHP Array work?

I want to find out how I can store small strings in an array and output them correct.
In this case I want to set a two-letter language code in an array at the top and
then output a string in that language later.
I really appreciate your help.
The following code I've made does not work but it's something like this I'm looking for:
<?php
// Set the language
$settings = array(
Language => "en"
);
// Set the strings
$locales = array(
Installed => array("en", "da"),
TheString => array("Dog", "Hund")
);
// Do some magic
$lang = $settings["Language"][0];
// Output Dog (or Hund if the language is "da")
echo $lang["TheString"];
?>
$settings = array( 'lanaguage' => 'en');
$locales = array(
'en' => array(
'dog' => 'dog'
),
'da' => array(
'dog' => 'hund'
)
);
// You don't need this, but you can get it like so:
$installed_languages = array_keys( $locales);
echo $locales[ $settings['language'] ]['dog'];
This will either output dog if $settings['language'] is en, or hund if it is da.

Drupal - PHP Validation

I have some content types (nodes) that are attached to various taxonomies. For specific node types, I want to do some validation on the taxonomy. I do not want to hard-code the nodes types and their corresponding fields that reference the taxonomy. So I put them in array.
However, I am unable to dereference the field names. I've tried double $$, quotes, etc, but can't get it to work. Is what I want to do possible?
Below is a standalone PHP that I am trying to get to work.
<?php
$node = (object) array(
'nid' => NULL,
'vid' => NULL,
'uid' => '1',
'type' => 'price_document',
'language' => 'und',
'field_taxonomy_price' => array(
'und' => array(
array(
'tid' => '94'
)
)
),
);
$nodes_to_check = array("price_document" => "field_taxonomy_price",
"package" => "field_taxonomy_package",
);
if (array_key_exists($node->type,$nodes_to_check)) {
$taxonomy_field = $nodes_to_check[$node->type];
print_r($taxonomy_field);
$tid = $node->field_taxonomy_price ['und'][0]['tid']; // <- this works but, how
//$tid = $node->"$$taxonomy_field" ['und'][0]['tid']; <- can I deref variable?
}
?>
Well, you can do this:
$taxonomy_field = $nodes_to_check[$node->type];
$tid = $node->{$taxonomy_field}['und'][0]['tid];
You don't need the double dollar signs. That's in case you want to do things like this:
$dog = "I am a dog";
$var = "dog";
$$var = "Now I'm a pussycat";
echo $dog; // Output: Now I'm a pussycat

PHP use default array to keep live array structured correctly

I have an array holding some default settings for my plugin. As the plugin evolves settings maybe removed or added from version to version.
Here is an example default array:
$defaults = array(
'setting1' => 'somevalue',
'setting2' => 'somevalue',
'setting4' => 'somevalue',
);
Here is an example of live settings data that the structure needs to be updated for the new $default structure:
$livesettings = array(
'setting1' => 'foo',
'setting2' => 'bar',
'setting3' => 'foobar',
);
I'm looking for a function where I can pass both arrays and the structure of the livesettings is updated to match the $defaults.
So in this case in livesettings:
setting1 and setting2 isn't touched. Their values stay intact
setting3 is removed as no longer needed
setting4 is added with the default value of somevalue
Are their any functions in PHP that can do this in one go? If yes what is it? If no how would I achieve this with PHP code?
You want a combination of array_intersect_key() and array_merge().
$livesettings = array_intersect_key($livesettings, $defaults);
$livesettings = array_merge($defaults, $livesettings);
The first function will remove all keys not found in $defaults, while the second would add items from $defaults not found in $livesettings
you don't need to a function for this problam, you can also use the $defaults like a base array,
$defaults = array(
'setting1' => 'somevalue',
'setting2' => 'somevalue',
'setting4' => 'somevalue',
);
$livesettings = $defaults; // it will be copited by value,
$livesettings['setting1'] = 'overriden setting 1';
$livesettings['setting3'] = 'added new setting to live config';

Need help about array

What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.

Categories