how explode country code from number php, i need 1-3 characters from number for country validation. I have array with ( code => country), i have script example, but it works only if i explode 1 character, but country code can be 2 or 3 characters too. i know that i can explode by $number = explode(" ", 1 777777); , but i need full number without additional symbols or spaces.
$number = "1777777";
$we = substr($number, 0, 2);
$countrys = array(
'1' => 'us',
'2' => 'uk',
'3' => 'de',
'44' => 'fi', // dont work if 2 characters..
'123' => 'no' // dont work if 3 characters..
);
$array = "$we";
echo $country = $countrys[$array[0]];
echo "<br>country";
how i can modificate this code? thank you! or any other suggestions?
I would assume if the number is like 123777777, the country code would be considered as 123 instead of 12 or 1, if both 1, 12 and 123 exist.
In this case, just start by checking the first 3 digits against the countrys array. If none is found, then go on by checking the first 2 digits, and so on.
$number = "123777777";
$countrys = array(
'1' => 'us',
'2' => 'uk',
'3' => 'de',
'44' => 'fi',
'123' => 'no',
);
$i = 3;
$country = "";
while ($i > 0) {
if (isset($countrys[substr($number, 0, $i)])) {
$country = $countrys[substr($number, 0, $i)];
break;
} else {
$i--;
}
}
echo $country;
In your code, you are always assigning the first country in $countrys to your $country. So you will always end up with us.
Instead of doing that, you should get the first 3, 2, or 1 digit(s) from your phone number, and check if the array key exists. If it does, you use that as the lookup index to your array.
Here's a pseudocode for you to get started:
perform a loop to get the first 3, 2, and 1 digit(s) from the phone number:
// Order is important as you want to match '123' before you match '1'
Check if the array key for the digit exists in the $countrys
If yes, get the country name and quit the loop
If not, go to the next less digit
If the key is found:
Print the country name
Else:
Print the country is not found
Here is partial code for how you'd do it for the 3 digits. You just need to add a loop (such as for-loop) to simplify your work.
$number = "123777777";
// Add your loop here to check for 3, 2, 1 digit
$we = substr($number, 0, 3);
$countrys = array(
'1' => 'us',
'2' => 'uk',
'3' => 'de',
'44' => 'fi',
'123' => 'no'
);
$array = "$we"; // You don't need this
if (array_key_exists ($we, $countrys))
{
// Remember to break out of your loop when the country is found
$country = $countrys[$we];
}
else
{
$country = "Non in list";
}
// End your loop here
echo "${we} is ${country}\n";
Use krsort to sort the array (longest numbers first). In this case "123" will be checked before "1". Then you can simply iterate over your array and check if the number begins with the country's number. If it matches, save the country code to a variable:
$number = '123777777';
$countrys = array(
'1' => 'us',
'2' => 'uk',
'3' => 'de',
'44' => 'fi',
'123' => 'no'
);
// sort the array by key, descending
krsort($countrys, SORT_NUMERIC);
// iterate over all countries
foreach ($countrys as $we => $ccode) {
// if number begins with current number
if (strpos($number, '' . $we) === 0) {
// store country code and break the loop
$country = $ccode;
break;
}
}
echo 'country: ' . $country; // expected: "no"
Related
I have a multidimensional array as follows, which is a PHP array of shoe sizes and their conversions...
$size_array = array(
"M"=>array(
'6'=> array('uk'=>'6','eu'=>'39.5','us'=>'7'),
'6H'=> array('uk'=>'6.5','eu'=>'40','us'=>'7.5'),
'7'=> array('uk'=>'7','eu'=>'40.5','us'=>'8'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'8.5'),
'8'=> array('uk'=>'8','eu'=>'42','us'=>'9'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'9.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'10'),
'9H'=> array('uk'=>'9.5','eu'=>'44','us'=>'10.5'),
'10'=> array('uk'=>'10','eu'=>'44.5','us'=>'11'),
'10H'=> array('uk'=>'10.5','eu'=>'45','us'=>'11.5'),
'11'=> array('uk'=>'11','eu'=>'46','us'=>'12'),
'11H'=> array('uk'=>'11.5','eu'=>'46.5','us'=>'12.5'),
'12'=> array('uk'=>'12','eu'=>'47','us'=>'13'),
'12H'=> array('uk'=>'12.5','eu'=>'48','us'=>'13.5'),
'13'=> array('uk'=>'13','eu'=>'48.5','us'=>'14')
),
"F"=>array(
'3'=> array('uk'=>'3','eu'=>'35.5','us'=>'5'),
'3H'=> array('uk'=>'3.5','eu'=>'36','us'=>'5.5'),
'4'=> array('uk'=>'4','eu'=>'37','us'=>'6'),
'4H'=> array('uk'=>'4.5','eu'=>'37.5','us'=>'6.5'),
'5'=> array('uk'=>'5','eu'=>'38','us'=>'7'),
'5H'=> array('uk'=>'5.5','eu'=>'38.5','us'=>'7.5'),
'6'=> array('uk'=>'6','eu'=>'39','us'=>'8'),
'6H'=> array('uk'=>'6.5','eu'=>'39.5','us'=>'8.5'),
'7'=> array('uk'=>'7','eu'=>'40','us'=>'9'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'9.5'),
'8'=> array('uk'=>'8','eu'=>'41.5','us'=>'10'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'10.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'11'),
'9H'=> array('uk'=>'9.5','eu'=>'43.5','us'=>'11.5'),
'10'=> array('uk'=>'10','eu'=>'44','us'=>'12')
)
);
The array is part of a function that returns the conversions based on a supplied size and gender (i.e. SizeConvert('M','6') returns Array ([uk] => 6, [eu] => 39.5,[us] => 7)).
I want to extend the function to allow the passing of a value which will return the array results with any .5 values replaced with ½ (or ½) (i.e. SizeConvert('M','6','Y') returns Array ([uk] => 6, [eu] => 39½,[us] => 7))
How do I make str_replace (or a more appropriate command) iterate over the array and replace the values?
I've tried something like str_replace(".5", "½", $size_array) but I guess that's not working as it's only looking at the initial array, not the sub-arrays.
You are trying to apply this to a multidimensional array without real reason. If you have your SizeConvert function ready and returning a one dimensional array, simply apply the transformation before returning the value:
function SizeConvert(/* other parameters */, bool $convertOneHalf) {
$match = ... // your code to find the match
return $convertOneHalf
? str_replace('.5', '½', $match)
: $match;
}
Based on the boolean value of the parameter that dictates whether the conversion should be applied, we either return the modified or the unmodified result through the ternary.
Do not overthink it and use a for loop to loop through all the elements in the array and use an if...else... to check for 0.5
if($array[index]=="0.5") {
$array[index]="½";
} else {
$array[index]=str_replace(".5", "½", $array[index]);
}
I coded up a simple code, it's not exactly the answer to your question but u can use the logic behind it. The code below will change all the 0.5 in the array to 1⁄2 but since u already acquire the data, there is no need to have so much nested-loop, just 1 level of the loop to loop through all ur elements in your array is enough.
<?php
$size_array = array(
"M" => array(
'6' => array(
'uk' => '6',
'eu' => '39.5',
'us' => '7'
) ,
'6H' => array(
'uk' => '6.5',
'eu' => '40',
'us' => '7.5'
) ,
'7' => array(
'uk' => '7',
'eu' => '40.5',
'us' => '8'
)
) ,
"F" => array(
'3' => array(
'uk' => '3',
'eu' => '35.5',
'us' => '5'
) ,
'3H' => array(
'uk' => '3.5',
'eu' => '36',
'us' => '5.5'
) ,
'4' => array(
'uk' => '4',
'eu' => '37',
'us' => '6'
)
)
);
foreach ($size_array as $firstLevel)
{
foreach ($firstLevel as $secondLevel)
{
foreach ($secondLevelas $values)
{
if ($values== "0.5")
{
echo $values= "½";
}
else
{
echo $values= str_replace(".5", "½", $values);
}
}
}
}
?>
I have an array with key and value pair. I'm building this array dynamically and below is the code.
$x[] = array('type_name' => $value->name,
'percentage'=> intval($percentage));
My intention is to get the maximum value and for that I do
max($x);
However it is returning the wrong value actually the lowest value. Following is my array. Any help would be awesome.
$x = array(
array(
'type_name' => 'type 1'
'percentage' => 10,
),
array(
'type_name' => 'type 2'
'percentage' => 15,
),
array(
'type_name' => 'type 3'
'percentage' => 45,
),
);
Thanks is advance.
From php max() documentation :
// Multiple arrays of the same length are compared from left to right
It means that if you want to compare "percentage" values first instead of "type_name" values, you'll have to change their order in the array.
So, you could build your array like this ("percentage" comes first) and it should work :
$x[] = array(
'percentage'=> intval($percentage),
'type_name' => $value->name
);
For example :
$x = array(
array(
'percentage' => 10,
'type_name' => 'type 1'
),
array(
'percentage' => 15,
'type_name' => 'type 2'
),
array(
'percentage' => 45,
'type_name' => 'type 3'
),
array(
'percentage' => 25,
'type_name' => 'type 4'
)
);
print_r(max($x));
Output :
Array
(
[percentage] => 45
[type_name] => type 3
)
Hope it helps.
You need to read how the max compares against different types of data. In your case, you are trying to compare against one of the array item i.e. percentage inside one of the item so the function max does not know to do this.
There is an example by Revo in the manual which shows you how to do this.
You are creating an array of arrays. max doesn’t know that your arrays should be compared by the 'percentage' key, so it can’t be used here.
Instead, find the maximum value yourself. For example, like this:
$maxPercentage = false;
foreach ($x as $item) {
if ($maxPercentage === false || $item['percentage'] > $maxPercentage) {
$maxPercentage = $item['percentage'];
}
}
Now, $maxPercentage will store maximum percentage. Of, if you want an item with maximum percentage, get it like this:
$maxPercentage = false;
$maxItem = false;
foreach ($x as $item) {
if ($maxPercentage === false || $item['percentage'] > $maxPercentage) {
$maxPercentage = $item['percentage'];
$maxItem = $item;
}
}
This question already has answers here:
Combinations Of String While Maintaining Order Of Words
(3 answers)
Closed 8 years ago.
This is my first question at this site, so I hope that I will be specific enough with this.
I need to transform a text string into several array with all different combinations of the 'words' and 'word phrases' in the text string.
So string would be like:
"Football match France 2013"
From this I want the following array:
array(
0 => array(
'Football',
'match',
'France',
'2013'
),
1 => array(
'Football',
'match',
'France 2013'
),
2 => array(
'Football',
'match France',
'2013'
),
3 => array(
'Football',
'match France 2013'
),
4 => array(
'Football match',
'France',
'2013'
),
5 => array(
'Football match',
'France 2013',
),
6 => array(
'Football match France',
'2013'
),
7 => array(
'Football match France 2013',
),
)
So the restriction that a each result string string may consist of 1 to n consecutive words and that in total each sub array should contain each word one time.
Here is some code that works.
<?php
$str = 'Football match France 2013'; // Initialize sentence
$words = explode(" ",$str); // Break sentence into words
$p = array(array(array_shift($words))); // Load first word into permutation that has nothing to connect to
foreach($words as $word) { // for each remaining word
$a = $p; // copy existing permutation for not-connected set
$b = $p; // copy existing permutation for connected set
$s = count($p); // cache number of items in permutation
$p = array(); // reset permutation (attempt to force garbage collection before adding words)
for($i=0;$i<$s;$i++) { // loop through each item
$a[$i][] = $word; // add word (not-connected)
$b[$i][count($b[$i])-1] .= " ".$word; // add word (connected)
}
$p = array_merge($a,$b); // create permutation result by joining connected and not-connected sets
}
// Dump the array
print_r($p);
?>
Hey all i am new at classes and arrays in php but need to find out how to go about getting the correct value from this class function array
class theCart {
public static $DISTANCE = array(
'0' => '0 - 75',
'10' => '76 - 125',
'20' => '126 - 175',
'30' => '176 - 225',
'40' => '226 - 275',
'50' => '276 - 325'
);
}
My output i am trying to match looks like this: 76 - 125
Do i just call it like
$distanceNum = '76 - 125';
$tmpDistanceTotal = $DISTANCE($distanceNum);
Should $tmpDistanceTotal then have a value of 10? I'm thinking that the array only has the values 0,10,20,30,40,50 in it?
I have another array:
public static $STEPS = array(
'0' => 0,
'1' => 0,
'2' => 0,
'3' => 25,
'4' => 50,
'5' => 75,
'6' => 100,
'7' => 125
);
My output i am trying to match with that above is 3 I'm not sure if its looking for a string or not?
This should clear the point:
foreach (theCart::$DISTANCE as $k => $v) {
if ($v == '76 - 125') {
echo $k;
break;
}
}
For $tmpDistanceTotal to get the value 10, you could do the following:
$tmpDistanceTotal = array_search($distanceNum, theCart::DISTANCE);
or you may wish to end up with something like this:
class theCart {
public static $DISTANCE = array(
'0' => '0 - 75',
'10' => '76 - 125',
'20' => '126 - 175',
'30' => '176 - 225',
'40' => '226 - 275',
'50' => '276 - 325'
);
public function getTotalDistance($distanceNum)
{
return array_search($distanceNum, self::DISTANCE);
}
}
Your question is actually just about arrays, and you should remove the classes from here to make things easier to understand:
$DISTANCE = array(
'0' => '0 - 75',
'10' => '76 - 125',
'20' => '126 - 175',
'30' => '176 - 225',
'40' => '226 - 275',
'50' => '276 - 325'
);
$variable = $DISTANCE[10];
In the above example Variable will be equal to 76-125. You're working with Associative Arrays, so you need to go read up on them a little bit as your questions shows you don't really understand how arrays work. Once you have that down, go ahead and move into a class context like you mentioned above.
You can check out the PHP Manual here: http://php.net/manual/en/language.types.array.php
For a short and quick answer you can use
$tempVar = 10;
$tmpDistance = $this->DISTANCE[$tempVar];
Not sure what you are trying to do, but you could use array_search:
$distanceNum = '76 - 125';
$key = array_search($distanceNum, theCart::$DISTANCE);
$key is now 10.
So we got the values (INT) :
V1 , V2 , V3 , V4
And the text :
Text1 , Text2 , Text3 , Text4
We will order the values and echo corespondent Text instead of values.
Let's take an example :
(variables) : V1 = 1 , V2 = 30 , V3 = 2 , V4 = 4
(text) : Banana , Cake , Apple , Patato
Will result ->
V1 , V3 , V4 , V2
after they are ordered but we will display text instead of our current result .
So the final echo is :
Banana , Apple , Patato , Cake . (will echo them into a table)
Note : Some of the values can be equal !
So far i tried with 3 arrays :
($text_array) text , ($arr1) V1[...] , and ($arr2) V1[...]
(same as second because I use sort($array); on it).
I tried to echo with :
echo $text_array[array_search($arr1[0], $arr2)];
but this will make the text repeat if values are the same.
I am sorry if I did not make myself clear ... it's really hard to explain.
#
UPDATE
#
It looks like this :
$V1 = $vars[1] + $vars[29] + $vars[30];
$V2 = $vars[6] + $vars[19] + $vars[40];
$V3 = $vars[14] + $vars[15] + $vars[44];
$V4 = $vars[0] + $vars[22] + $vars[37];
..........................................
$V15 = $vars[3] + $vars[28] + $vars[31];
Text array :
$valori = array(("Altruismul", "Simtul estetic", "Creativitatea", "Stimularea intelectuala", "Reusita obiectivata", "Independenta", "Prestigiul", "Conducerea altora", "Avantajele materiale", "Siguranta", "Ambianta de la locul de munca", "Relatiile cu superiorii", "Relatiile cu colegii", "Stilul de viata pe care-l asigura profesia", "Varietate");
Tried :
$arr = array("Altruismul" => $V1 , "Simtul estetic" => $V2 , "Creativitatea" => $V3 , "Stimularea intelectuala" => $V4 , "Reusita obiectivata" => $V5 , "Independenta" => $V6 , "Prestigiul" => $V7 , "Conducerea altora" => $V8 , "Avantajele materiale" => $V9 , "Siguranta" => $V10 , "Ambianta de la locul de munca" => $V11 , "Relatiile cu superiorii" => $V12 , "Relatiile cu colegii" => $V13 , "Stilul de viata pe care-l asigura profesia" => $V14 , "Varietate" => $V15);
asort($arr);
Did not work well.
I'm guessing what you're trying to say is that you have two arrays that are linked, and you want to sort one and use that sorting to output the second. If so, try this:
$amount = array(1 => 1, 2 => 30, 3 => 2, 4 => 4);
$food = array(1 => 'Banana', 2 => 'Cake', 3 => 'Apple', 4 => 'Patato');
asort($amount);
foreach($amount as $key => $val) {
echo "{$food[$key]} - $val\n";
}
Or alternatively:
$food = array('Banana' => 1, 'Cake' => 30, 'Apple' => 2, 'Patato' => 4);
asort($food);
foreach($food as $item => $val) {
echo "$item - $val\n";
}
First, make sure you have a unique set of keys:
$texts = array_unique($texts); // assuming $texts is your foods
Then, you want to combine the two:
$combined = array_combine($texts,
array($v1, $v2, $v3, $v4 /* ... you get the idea */);
Then, you want to sort based on the keys:
ksort($combined);
Then you can print in order:
foreach($combined as $food, $val)
{
echo "$food is at $val";
}
If you don't like ksort, you can always reverse the order of the arrays in the array_combine function and then simply use regular sort.
If your values are unique, then you can use an associative array:
<?php
$data = array(
1=>"Banana",
2=>"Apple",
4=>"Patato",
30=>"Cake");
//sort the data by the keys if you want
aksort($data);
//Then access it like normal
echo $data[2]; //outputs "Apple"
If your values are not unique, then you are going to have a harder time. One way is to use a multidimensional array with a lookup function.
<?php
$data = array(
array(1,"Banana"),
array(2,"Apple"),
array(4,"Patato"),
array(30,"Cake")
);
echo lookup($data,30); //Outputs "Cake"
function lookup($arr,$key) {
foreach($arr as $a) {
if($a[0] == $key)
return $a[1];
}
return NULL;
}
And you would want to modify the lookup() function to handle the duplicate values like you want, my function is just going to output the first one it finds.
$int_array = array('$v1' => 2 , '$v2' => 30 , '$v3' => 4 , '$v4' => 10);
$string_array = array('banana' , 'cake' , 'apple' , 'potato');
//First , sort the int_array by value. (low to hight)
$int_array = asort($int_array);
//Second , echo string according to sorted int_array
foreach($int_array as $v => $num)
{
echo $string_array[ substr($v , 2 , 1) - 1 ];
}
Works for you?
Did you see array_multisort()? It will sort multiple column arrays without breaking their correspondence, which looks like what you want.
Though nowadays I have a strong preference for row arrays, which is how most tabular data is stored in programming languages and is thus a more 'natural' way:
array(
array('variable' => 1, 'text' => 'Banana'),
array('variable' => 30, 'text' => 'Cake' ),
...
)
(add or remove arrays or indirection as per your liking, but the invariant is that mainArray[0] contains a full row's worth of data (i.e. both V1 and Text1 in some array hierarchy))
...and use a functional sort:
usort($mainArray, function($left, $right) {
if ($left['variable'] < $right['variable'])
return -1;
else if ($left['variable'] == $right['variable'])
return 0;
else
return +1;
});