PHP letter value in For Loop [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having problems with my PHP code, I am trying to display a string with a value. For example, A = 1, B = 2. So if I had a string value of Cat, it would display a value of 3120 and also would add all the values together.
Many Thanks,
Jonathan

You can use ord() to get ASCII value and subtract 96. Example:
$str = 'cat';
$val = strtolower($str);
for($i = 0; $i < strlen($str); $i++){
echo ord($val[$i]) - 96;
}
strtolower() to convert lower case latter.

Create an associative array. Keys should be the letters, and values should store the values.
Get the letters, and get the value, and concat them into a new string:
$string = 'Cab';
$lettersArray = array(
'a' => 1,
'b' => 2,
'c' => 3,
//and so on
);
$valueString = '';
for ($i=0; $i < strlen($string); $i++) {
$letter = strtolower(substr($string,$i,1));
$valueString .= $lettersArray[$letter];
}
echo $valueString;
Output is:
312

Organize letter and value in a array
$letters = array(
'a' => 1
, 'b' => 2
, ...
);
loop the string
$string = "cat";
$sum = 0;
for($i = 0; i<strlen($string);$i++) {
$index = $string[$i];
$sum += $letters[$index];
print $letters[$index];
}
finally, print the sum
print $sum;

Related

Get character type of each character in a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Let's say I have a string like A10-53 c and I want to get the character type of each character in an output array.
Something like:
Array
(
[0] => string
[1] => number
[2] => number
[3] => symbol
[4] => number
[5] => number
[6] => space
[7] => string
);
I could make something like:
$str = 'A10:53 c';
$arr = str_split($str);
$str_length = count($arr);
$res = array();
for($i=0; $i<$str_length; $i++){
if(ctype_space($arr[$i])){
$res[$i] = 'space';
}elseif(is_numeric($arr[$i])){
$res[$i] = 'number';
}elseif(is_string($arr[$i])){
$regex = preg_match('/[^a-zA-Z\d]/', $arr[$i]);
if($regex){
$res[$i] = 'symbol';
}else{
$res[$i] = 'string';
}
}else{
$res[$i] = "N/A";
}
}
print_r($res);
Is there something better than this method?
You actually don't need regex for this. The ctype_ functions will do the job for single-byte characters and it will be very easy to read (I cannot promise the same of my regex snippet).
Code: (Demo) (an implementation using your sample input)
$tests = ['A', 'z', '+', '0', '8', '*', ' '];
foreach ($tests as $test) {
echo "\n{$test}: ";
if (ctype_alpha($test)) {
echo 'letter';
} elseif (ctype_digit($test)) {
echo 'number';
} elseif (ctype_space($test)) {
echo 'space';
} else {
echo 'symbol';
}
}
And here is a demonstration of a regex that accommodates multibyte characters as well.
It is a minor adjustment to another answer of mine.
To convert your input string to an array, just call str_split() (or mb_str_split())
Code: (Demo)
$lookup = ['symbol', 'letter', 'number', 'space'];
$tests = ['A', 'z', '+', '0', 'ǻ', 'Ͱ', ' ', '₉'];
foreach ($tests as $test) {
$index = preg_match('~(\pL)|(\pN)|(\pZ)~u', $test, $out) ? array_key_last($out) : 0;
echo "{$test}: {$lookup[$index]}\n";
}
Output
A: letter
z: letter
+: symbol
0: number
ǻ: letter
Ͱ: letter
: space
₉: number
p.s. If you are not entertaining multibyte characters, then this pattern will do: ~([a-z])|(\d)|( )~i

Duplicate words in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have probably information about whether it is available in PHP to detect a duplicate and a book about not removing it and adding it to -1, -2, -3
Example:
$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
Result:
$output = 'H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2'
$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$parts = explode(',', $string); // split by comma
$used = []; // array to count the number of occurrences
$result = []; // array to take the "new" elements
foreach($parts as $part) {
if(isset($used[$part])) { // if there is an entry in the counter array already,
// increment it by one,
$used[$part]++;
}
else { // else initialize with 0
$used[$part] = 0;
}
// put part into new array, append -(counter) if counter > 0
$result[] = $part . ($used[$part] ? '-'.$used[$part] : '');
}
echo implode(',', $result); // join together with comma
Pretty much the same as misorude's answer.
<?php
$string = 'H4,H4,H3,WY21W,W5W,W5W,WY21W,W21/5W,W21/5W,W21W,W16W,W5W';
$values = explode(',', $string);
foreach($values as $k => $value)
if($counts[$value] = !isset($counts[$value]) ? 0 : $counts[$value]-1)
$values[$k] = $value . $counts[$value];
print implode(',', $values);
Output:
H4,H4-1,H3,WY21W,W5W,W5W-1,WY21W-1,W21/5W,W21/5W-1,W21W,W16W,W5W-2

Sorting integer value in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have 19 variables in a php file.
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
.....
.....
$s = 32;
What i need, I need to show only top 5 value. And there is similar value for some variables. In that case, I need to show the first value only if it is in the top 5 value.
I am not having any clue on doing this.
After receiving some feedback given bellow, i have used array and asort
Here is the example-
<?php
$fruits = array("a" => "32", "b" => "12", "c" => "19", "d" => "18");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
The output looks like this:
b = 12 d = 18 c = 19 a = 32
I need the reverse result. Meaning, 32, 19, 18, 12.....
Any help. Just dont know the exact command
This is best done by putting the values of the variables into an array and running
sort($arr); (this is from lowes to highest).
rsort($arr); sorts high to low.
http://php.net/manual/en/array.sorting.php
Then you can get the first values at array-index 0,1,2,3 and 4 which will be the biggest numbers.
So:
$arr= array ($a,$b,$c, ....);
rsort($arr);
var_dump($arr); // gives the output.
$arr[0] // biggest number
$arr[4] // 5th biggest number.
A funny way to do this:
$a = 20;
$b = 23;
$c = 2;
$d = 92;
$e = 51;
$f = 27;
$g = 20;
$h = 20;
$array = compact(range('a', 'h'));
rsort($array);
foreach(array_slice($array, 0, 5) as $top) {
echo $top, "\n";
}
Output
92
51
27
23
20
Demo: http://3v4l.org/Wi8q7
Do they need to be individual variables? Storing the values in an array is a better option. So, either manually put all the variables into an array, or change your structure to something more like:
$arr = array(
'a' = 20,
'b' = 23,
'c' = 2,
'd' = 92,
'e' = 51,
....
....
's' => 32
);
or similar. Then use sort() to sort the array:
sort($arr);
To get the top 5, use array_slice():
$arr = array_slice($arr, 0, 5);
See demo
Note: sort() may not be best option for you depending on the desired result. For other sorting options, consult the manual: http://php.net/manual/en/array.sorting.php
<?php
array_push($data,$a);
array_push($data,$b);
.
.
.
$sorted_array = usort($data, 'mysort');
$top5 = array_splice($sorted_array,5);
if(in_array($your_variable,$top5)){
return $top5[0];
}else {
return $top5;
}
function mysort($a,$b){
if ($a == $b) {
return 0;
}
return ($a < $b) ? 1 : -1;
}
?>
$array=array();
for ($i=97;$i<=115;$i++){ //decimal char codes for a-s
$var =chr($i);
$array[]= $$var; //variable variable $a- $s
}
asort($array);
var_dump($array);

How to Adding values of two dimnetional array in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have the below given array
Array
(
[0] => 2,3
[1] => 2,3
)
I want to sum up and get result in a variable. E.g. variable a = 4 (2+2=4) and variable b = 6 (3+3=6). I am coding in php.
Use EXPLODE inside foreach
<?php
$yourArr = array('2,3','2,3');
$a = 0;
$b =0;
foreach ($yourArr as $temp)
{
$tempnew = explode(",",$temp);
$a += $tempnew[0];
$b += $tempnew[1];
}
echo "a = ".$a."<br>";
echo "b = ".$b;
?>
Try this
$a = 0;
$b =0;
foreach ($yourArr as $temp)
{
$a += $temp[0];
$b += $temp[1];
}
echo "a = ".$a."<br>";
echo "b = ".$b;
Output
a = 4
b = 6

How to make an array of elements which not in range of another array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
There is an array of numbers from 0 to 10000
$a = array();
$a = range(0,10000);
I have some values which are dynamic coming from database are in array like
$b = array("100-200","400-500","700-900");
so basically i want an array that will look like
array("0-100","200-400","500-700","900-10000");
for example-> if i started a value from 0 so it will break on 100.so i will get 0-100 as first element of an array,then nothing will happen until 200.Again 200 the value will start and go to 400 and will stop then i get 200-400.After that nothing will happen until 500.it will again start with 500 and will stop on 700.so i will get third element as 500-700 and so on...
Anybody can help?
if you want your ranges to be as string element of array, try this:
<?php
$b = array("400-500","700-900","100-200");
asort($b);//new line to sort the ranges
$MIN = 0;
foreach($b as $rang){
$limits = explode('-', $rang);
$result[] = $MIN." - ".$limits[0];
$MIN = $limits[1];
}
$result[] = $MIN." - 10000";
print_r($result);
?>
You can try something like this
<?php
$b = array( "100-200","400-500","700-900" );
$c = array();
$starting = 0;
$ending = 100000;
$last = $starting;
$a = array(); // not being used
$a = range( $starting, $ending ); // not being used
foreach( $b as $k => $v )
{
$values = explode( '-' , $v);
if ( $values[0] > $starting && $values[0] < $ending )
{
$c[] = $last.'-'.$values[0];
$last = $values[1];
if ( $last <= $ending && $k == count( $b ) -1 )
{
$c[] = $last.'-'.$ending;
}
}
}
print_r( $c );
?>
Please bear in mind that I did not use the original $a array for anything. I don't understand it's purpose, unless it's not actually generated from a range, and if so this could should be changed as well

Categories