Change languages in PHP echo or print - php

Please help me to solve this issue. I'm not sure is it possible or not! I need a small tricky solution.
<?php include_once"system/hijri_calendar.php";
echo (new hijri\datetime()) -> format ('_j');
?>
Above code gives me an output of integer (1...30) in English.
Now, After echo, I want to change this English language to other languages.
Example:
Say Above code gives me an output 1
I want to change this output (1) to other languages (১)

If I get you right you are trying to get the value from one array based on the value and key from another array. You can use array_search() to find the key from array based on value
<?php
$en = array(1,2,3,4,5,6,7,8,9,0);
$bn = array('১','২','৩','৪','৫','৬','৭','৮','৯','০');
var_dump(array_search(5, $en)); // gives the key 4 from $en where value is 5
// array keys strart with 0
// so you can do
var_dump($bn[array_search(5, $en)]); // gives ৬
PHPFiddle to play with

Quick and dirty:
function __($number, $lang)
{
if ($lang == 'en') {
return $number;
}
$translate = array();
$translate['bn'] = array(
'1' => '১',
'2' => '২',
'3' => '৩',
'4' => '৪',
'5' => '৫',
'6' => '৬',
'7' => '৭',
'8' => '৮',
'9' => '৯',
'0' => '০'
);
$translate['th'] = array(
'1' => '๑',
'2' => '๒',
'3' => '๓',
'4' => '๔',
'5' => '๕',
'6' => '๖',
'7' => '๗',
'8' => '๘',
'9' => '๙',
'0' => '๐'
);
$digits = str_split($number,1);
$return_this = '';
foreach($digits as $digit){
$return_this .= $translate[$lang][$digit];
}
return $return_this;
}
echo __('905','bn');
Break down, if the lang is en you get what you give, if bn or th, it'll break the number apart and rebuild it using the requested array.
This is basically how I do I18n except the arrays for each language are in their own files.

I've changed the arrays slightly to simplify things. If the array is in the order of the digits (so I've moved the 0 element to position 0 in the array) you can use...
$bn = array('০','১','২','৩','৪','৫','৬','৭','৮','৯');
$in = "18";
$out = "";
foreach ( str_split($in) as $ch ) {
$out .= $bn[$ch];
}
echo $out;

Related

randomize value in array for specific key

I'm trying to get a random array for specific key.
this is my code so far,
$convert = array(
'a' => 'Amusing','Amazing',
'b' => 'Beyond',
'c' => 'Clever','Colorful','Calm',
'd' => 'Dangerous','Donkey',
'e' => 'Endangered',
'f' => 'Fancy',
'g' => 'Great',
'h' => 'Helpful','Humorous',
);
$txt="baca";
$txt=strtolower($txt);
$arr=str_split($txt);
foreach ($arr as $alfa) {
echo $alfa." = ".$convert[$alfa]."\n";
}
the output would be :
b = Beyond
a = Amusing
c = Clever
a = Amusing
but I'm trying to get
b = Beyond
a = Amusing
c = Clever
a = Amazing
Unique value for specific array ('a') in this case.
I tried to use array_rand but failed. I would appreciate any advice given..
This:
array(
'a' => 'Amusing','Amazing',
...
)
is equivalent to:
array(
'a' => 'Amusing',
0 => 'Amazing',
...
)
You're not specifying a key for the word "Amazing", so it automatically gets a numeric key. It does not in any way actually belong to the 'a' key, even if you write it on the same line.
What you want is:
array(
'a' => array('Amusing', 'Amazing'),
...
)
And then:
$values = $convert['a'];
echo $values[array_rand($values)];

PHP Merging Arrays and presenting output in dot points

The output of the following code gives: MilkYoghurtCheese AppleOrangeBanana. Being new to php, I am having difficulty producing these elements as dot points in a list, rather than combined words in a sentence.
Is there a way to put these into dot points?
<?php
$newArray =array();
$DairyArray=array();
$FruitArray=array();
$DairyArray= array(
'1' => 'Milk',
'2' => 'Yoghurt',
'3' => 'Cheese',
);
$FruitArray = array(
'9' => 'Apple'
'10' => 'Orange',
'11' => 'Banana',
if ($_POST['Dessert'] == 'Yes') //This represents the condition that a checkbox is
checked
{
$newArray = array_merge($DairyArray, $FruitArray);
foreach ($newArray as $key => $value)
{
echo $value >;
}
}
What I am trying to achieve as output:
• Milk
• Yogurt
• Cheese
• Apple
• Orange
• Banana
Any help would be greatly appreciated, and I will try to see if I can answer some of your questions too.
Thanks
Andrew
The echo command only outputs the raw data in the variable (in your case array). You want to pimp it out a bit for a nice display like this:
$newArray = array_merge($DairyArray, $FruitArray);
echo "<ul>";
foreach ($newArray as $key => $value)
{
echo "<li>" . $value . "</li>";
}
echo "</ul>";
Keep in mind that HTML by default requires explicit instructions on how to display something, and omits line breaks, more than one space at a time and many other things. When we deal with data in variables, for the most part, they are generally the raw data without any formatting. You will always need to make it formatted nicely for your web pages - or get used to horrible text only pages :)
Use implode instead of foreach
<?php
$DairyArray= array(
'1' => 'Milk',
'2' => 'Yoghurt',
'3' => 'Cheese'
);
$FruitArray = array(
'9' => 'Apple',
'10' => 'Orange',
'11' => 'Banana'
);
$newArray = array_merge($DairyArray, $FruitArray);
echo ".".implode(".",$newArray);
?>
Also if you want to use bullet then you can use
<?php
echo "<ul><li>";
echo implode("</li><li>",$newArray);
echo "</li></ul>";
?>
<style>
ul li { float:left; margin-right:25px; }
</style>

How do I return the key of a certain value in an array?

I have an array that I am using to display form dropdown options. I would like to be able to display the key of a specified array element.
$options = array(
'10' => '10 Results',
'15' => '15 Results',
'20' => '20 Results',
'25' => '25 Results',
'30' => '30 Results'
);
If I use
$selected = '25';
echo $options[$selected]
this of course returns "25 Results". How would I return the key of that element?
key($options)
The above would just return the key of the first element of the array.
Well, since you are defining the key, it's a pretty easy one...
echo $selected;
http://php.net/manual/en/function.array-search.php
In this case, you could use
$key = array_search('25 Results',$options)
to find the key that matches the value.
One easy way is to use array_flip:
$options = array(
'10' => '10 Results',
'15' => '15 Results',
'20' => '20 Results',
'25' => '25 Results',
'30' => '30 Results'
);
$reverseoptions = array_flip($options);
Then just do $reverseoptions['30 Results']; //returns 30;
Limitations exist. You can only do this with a simple array; it cannot be recursive without doing a little more code to make that happen.
Also, if any values are alike, the later one will replace the first.
$test = array('1'=>'apple', '2'=>'pear','3'=>'apple');
$testflip = array_flip($test);
print_r($testflip);
//Outputs Array ( [apple] => 3 [pear] => 2 )
I do this often to convert database representations to readable strings.
An alternative to array_search is to use a foreach loop! This is in case you do not know what the key is beforehand.
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
You can access the keys of the array and do as you wish with them. This will come in handy for doing database conversions as you mentioned.

String comparison with alternate character variables

Right to the problem...user need to input text (to be specific the input text is serial number), this input must be compared with database. However because of small print user will make mistake between characters like: (B/8), (1/l),(0,o),(u,v).
The question is how to make the user input "l234B" a valid entry when the serial number is "12348"??
here is another examples: o12u3 ---> 012v3
thanks.
Some solution might be to replace all occorences like "8" by "[8B]" to match against both possibilities:
$sn = "l234B"; $sn_new = "";
$problematic_chars = ['B' => 'B8', '8' => 'B8', '1' => '1l', 'l' => '1l', ...];
// Go through original string and create new string
// "l234B" becomes "[1l]234[8B]"
for($i = 0; $i < strlen($sn); $i++) {
$char = $sn[$i];
if (array_key_exists($char, $problematic_chars)) {
$sn_new .= "[".$problematic_chars[$char]."]";
} else {
$sn_new .= $char;
}
}
// Query stuff
$sql = "SELECT * FROM table_name WHERE sn REGEXP '^${sn_new}\$'";
Did not write PHP for long time, but I think you get the idea.
You may want to try similar_text function rather than using regular expressions and validate only non-ambiguous chars.
// to query
$id = "ABF8...";
// all combinations pre-generated
$c = array(
array('B' => 'B', '8' => '8', ...),
array('B' => 'B', '8' => 'B', ...),
array('B' => '8', '8' => '8', ...),
array('B' => '8', '8' => 'B', ...),
...
);
// generating all versions
foreach($c as $v)
{
$ids[] = strtr($id, $v);
}
the optimal solution depends on your specific setup. but probably you will have the IDs somewhere and you have to query them. so you will have to replace the ambigiuous chars in all possible combinations and query those.
strtr()

Running calculations on multi-dimensional arrays?

This is probably a real simple question but I'm looking for the most memory efficient way of finding out data on a particular multi-dimensional array.
An example of the array:
[0] => Array(
[fin] => 2
[calc] => 23.34
[pos] => 6665
)
[1] => Array(
[fin] => 1
[calc] => 25.14
[pos] => 4543
)
[2] => Array(
[fin] => 7
[calc] => 21.45
[pos] => 4665
)
I need a method of identifying the values of the following things:
The max 'calc'
The min 'calc'
The max 'pos'
The min 'pos'
(you get the gist)
The only way I can think of is manually looping through each value and adjusting an integer so for example:
function find_lowest_calc($arr) {
$int = null;
foreach($arr['calc'] as $value) {
if($int == null || $int > $value) {
$int = $value;
}
}
return $int;
}
The obvious drawbacks of a method like this is I would have to create a new function for each value in the array (or at least implement a paramater to change the array key) and it will slow up the app by looping through the whole array 3 or more times just to get the values. The original array could have over a hundred values.
I would assume that there would be an internal function to gather all of (for example) the 'calc' values into a temporary single array so I could use the max function on it.
Any ideas?
Dan
$input = array(
array(
'fin' => 2
'calc' => 23.34
'pos' => 6665
),
array(
'fin' => 1
'calc' => 25.14
'pos' => 4543
),
array(
'fin' => 7
'calc' => 21.45
'pos' => 4665
)
);
$output = array(
'fin' => array(),
'calc' => array(),
'pos' => array(),
);
foreach ( $input as $data ) {
$output['fin'][] = $data['fin'];
$output['calc'][] = $data['calc'];
$output['pos'][] = $data['pos'];
}
max($output['fin']); // max fin
max($output['calc']); // max calc
min($output['fin']); // min fin
There is no way to speed that up, besides calculating all three values at once. The reason for this is that you always need to loop through the array to find the sub-arrays. Even if you find a bultin function, the time complexity will be the same. The only way to make a real difference is by using another datastructure (i.e, not any of the bultin ones, but one you write yourself).
How are you receiving the array? If it is your code which is creating the array, you could calculate the minimum and maximum values as you are reading in the data values:
$minCalc = null;
$arr = array();
for(...){
//read in 'calc' value
$subArr = array();
$subArr['calc'] = //...
if ($minCalc === null || $minCalc > $subArr['calc']){
$minCalc = $subArr['calc'];
}
//read in other values
//...
$arr[] = $subArr;
}
Also, in your find_lowest_calc function, you should use the triple equals operator (===) to determine whether the $int variable is null. This is because the statement $int == null will also return true if $int equals 0, because null equals 0 when converted to an integer.
You don't have to crate a new function for each value, just pass the key you want in the function
function find_lowest($arr, $indexkey) {
$int = null;
foreach($arr[$indexkey] as $value) {
if($int == null || $int > $value) {
$int = $value;
}
}
return $int;
}
As php is not type-safe, you should be fine passing both string or int index

Categories