I have this array which links numbers to letters at the moment like this:
1-26 = A-Z
But there is more, 27=AA and 28=AB etc...
so basically when I do this:
var_dump($array[2]); //shows B
var_dump($array[29]); //shows AC
Now this array I made myself but it's becoming way too long. Is there a way to actually get this going on till lets say 32? I know there is chr but I dont think I can use this.
Is there an easier way to actually get this without using this way too long of an array?
It's slower calculating it this way, but you can take advantage of the fact that PHP lets you increment letters in the same way as numbers, Perl style:
function excelColumnRange($number) {
$character = 'A';
while ($number > 1) {
++$character;
--$number;
}
return $character;
}
var_dump(excelColumnRange(2));
var_dump(excelColumnRange(29));
here is the code which you are looking for :
<?php
$start = "A";
$max = 50;
$result = array();
for($i=1; $i<=$max; $i++) {
$result[$i] = $start++;
}
print_r($result);
?>
Ref: http://www.xpertdeveloper.com/2011/01/php-strings-unusual-behaviour/
This should work for you:
Even without any loops. First I calculate how many times the alphabet (26) goes into the number. With this I define how many times it has to str_repleat() A. Then I simply subtract this number and calculate the number in the alphabet with the number which is left.
<?php
function numberToLetter($number) {
$fullSets = (($num = floor(($number-1) / 26)) < 0 ? 0 : $num);
return str_repeat("A", $fullSets) . (($v = ($number-$fullSets*26)) > 0 ? chr($v+64) : "");
}
echo numberToLetter(53);
?>
output:
AAA
Related
In need of some help - am trying to analyse news articles.
I have a list of positive words and negative words. I am search the article contents for instances of the words a counting the up.
my problem is that the negative word list is a lot long that the positive so all the results a skewed to negative.
I am looking for a way to normalise the results so a positive word is weighted slightly against the negative to even out the fact that is a considerably high chance of finding a negative word. Unfortunately I have no idea where to start.
Appreciate you taking the time to read this.
Below is the code I have so far.
function process_scores($content)
{
$positive_score = 0;
for ($i = 0; $i < count($this->positive_words); $i++) {
if($this->positive_words[$i] != "")
{
$c = substr_count( strtolower($content) , $this->positive_words[$i] );
if($c > 0)
{
$positive_score += $c;
}
}
}
$negative_score = 0;
for ($i = 0; $i < count($this->negative_words); $i++) {
if($this->negative_words[$i] != "")
{
$c = substr_count( strtolower($content) , $this->negative_words[$i] );
if($c > 0)
{
$negative_score += $c;
}
}
}
return ["positive_score" => $positive_score, "negative_score" => $negative_score];
}
So I don't know php, but this seems less like a php question and more of a question of method. Right now when you analyze an article, you assign words as positive or negative based on whether or not they are in your dictionary, but because your dictionaries are of different sizes, you feel like this isn't giving you a fair analysis of the article.
One method you could try is to assign each word in the article a value. If a word does not exist in your dictionary, have the program prompt for manual interpretation of the word through the command line. Then decide whether the word is positive, negative, or neutral, and have the program add that word to the appropriate dictionary. This will be really annoying at first, but English speakers use roughly the same 2000 words for almost all of our conversation, so after a few articles, you will have robust dictionaries and not have to worry about skew because every single word will have been assigned a value.
I would suggest just throwing in a weighting factor to the output. The exact weighting is determined by trial and error. I went ahead and refactored your code since there was some repetition
<?php
class WordScore {
private $negative_words = [];
private $positive_words = [];
private $positive_weight = 1;
private $negative_weight = 1;
public function setScore(float $pos = 1, float $neg = 1) {
$this->negative_weight = $neg;
$this->positive_weight = $pos;
}
public function processScores($content) {
$positive_score = $this->countWords($content, $this->positive_words);
$negative_score = $this->countWords($content, $this->negative_words);
return [
"positive_score" => $positive_score * $this->positive_weight,
"negative_score" => $negative_score * $this->negative_weight
];
}
private function countWords( string $content, array $words, float $weight = 1 ) {
$count = 0;
foreach( $words as $word ) {
$count += substr_count( strtolower($content) , strtolower($word) );
}
return $count;
}
}
working example at http://sandbox.onlinephpfunctions.com/code/19b4ac3c12d35cf253e9fa6049e91508e4797a2e
So while i was doing my homework i stuck on one point.
The excercise is based on making a function which checks if $word is a palindrome, from my tests $L works and is moving forward to right side of the word ($L starts from left, $R from right)
but $R is not working at all, if $R is swapped by a number - it works. If $R is printed, it shows right number - 5.
$word = "madam";
function palindrome($s)
{
$i = intval(strlen($s) / 2);
$L = 0;
$R = strlen($s);
$pal = true;
for($i; $i>0; $i--)
{
if($s[$L] != $s[$R]) $pal=false;
$L++;
$R--;
}
if($pal==true)
print("palindrome");
else
print("not a palindrome");
}
palindrome($word);
I expect to make $R an value, i suspect that PHP sees it as a string, not an integer, but i don't know why. I would be very happy if someone helped me with that.
If you consider string as char table, index starts at 0, but strlen count from 1 so if you have 'madam' then strlen() returns 5 but last chatacter is on $s[4], simply use:
$R = strlen($s)-1;
As a quick, off the top of my head sort of idea... no loops, just some simple string splitting, this works to check if the given string ($s) is a palindrome.
function palindrome($s) {
// split the string in two
$left = substr($s, 0, floor(strlen($s)/2));
$right = substr($s, 0-strlen($left));
// if the left half matches the REVERSE of the right
// you've got a palindrome
return $left === strrev($right);
}
$word = "madam";
echo palindrome($word) ? "Yup" : "Nope";
Basically, it just chops the word in half - reverses the right half and compares it to the left. If they match, it's a palindrome - currently it's case-sensitive though so "Madam" won't be a palindrome but that can be easily tweaked by lower-casing the whole thing first.
I have a text file, and I need to pick a random string that is over 6 characters and under 10 characters. Normally, I would use a script like this, which would work, but since it needs to be a certain length, that won't work. Does anybody have a solution to this?
A sample input would be something like this:
Apple
Banana
Orange
Strawberry
Blueberry
Pineapple
Somelongfruithere
Those values would be in a .txt file, each with a line break. An example of a string that would be allowed is pineapple, but apple or Somelongfruithere wouldn't be allowed.
You'll need to do something like this:
$lines = array();
$tmpLines = file('random.txt');
for($i = 0; $i < count($tmpLines); ++$i)
{
if(strlen($tmpLines[ $i ]) > 6 && strlen($tmpLines[ $i ]) < 10)
{
$lines[] = $tmpLines[ $i ];
}
}
$randomWord = $lines[ array_rand($lines) ];
A shorter way, in number of lines, goes like this (but is much less safe):
$randomWord = '';
$lines = file('random.txt');
while(strlen($randomWord) <= 6 || strlen($randomWord) >= 10)
$randomWord = $lines[ array_rand($lines) ];
The first option gets all the lines in the file, and copies only the ones between 6 and 10 chars in length to another array. When choosing a random element from this array, you are "guaranteed" a reasonable access time for any random string.
The second option simply continues to pick a random string until one of the proper length is chosen, but could potentially take a while depending on the random number generator's mood. Unlikely, but I wouldn't want to risk it. Always take reliability as the best approach, in my book.
I would say explode the text file into a variable, run your random generator to get a placement value (position of the random string) then in a loop (a do/while loop), pull the string from the exploded variable, and check it's length to ensure it's what you want
if (strlen($rand_word) > 6 && strlen($rand_word) < 10) {
//execute function and end loop
} else {
// keep checking using a new random placement number
}
The answer depends on the requirement.
If you need to select from a group of strings and only accept one that fits your criteria, then you'll need to use strlen and try again if it is not the correct length.
Otherwise, you're still going to need strlen, to make sure it is at least 6 Chars, but then you can use substr to cut it to 10. If whitespace does not count, use ltrim & rtrim before strlen and substr.
First find all the words that are in the right character range, then pull a random one from the resulting array:
$fileLines = file('somefile.txt');
$myWords = array();
foreach ($fileLines as $line)
{
$thisLine = split(" ",$line);
foreach ($thisLine as $word)
{
$length = strlen($word);
if ($length > 6 && $length < 10)
{
$myWords[] = $word;
}
}
}
$randomWord = $myWords[array_rand($myWords)];
Shortened way!
for ($i=7; $i<=9; $i++)
if (strlen($str) == $i )
echo "bingo! " . strlen($str);
I'm making a simple yahtzee script in PHP, I've got up the final point where it checks the 5 dice for a result at the end.
The 5 dice sides are stored in an array, example $dice (2,5,2,7,8)
I'm not that experienced in working with arrays, but is there easier ways to compare each number, to like find instances of 2 the same, 3 the same, all the same etc?
array_search() ?
array_count_values() might be a function that's worth looking at. It will count the number of instances of a value in an array.
Example:
$dice = array(2,5,2,7,7);
$count = array_count_values($dice);
if($n = array_keys($count, 2))
{
// 2 of a kind
// $n = array(2, 7)
}
if(array_keys($count, 4))
{
// 4 of a kind
}
if(array_keys($count, 2) && array_keys($count, 3))
{
// Full House
}
Just count them.
for ($i=0; $i<count($dice); $i++)
$counter[$dice[$i]]++;
Use:
var_dump(array_count_values($array));
For an ecommerce site I want to generate a random coupon code that looks better than a randomly generated value. It should be a readable coupon code, all in uppercase with no special characters, only letters (A-Z) and numbers (0-9).
Since people might be reading this out / printing it elsewhere, we need to make this a simple-to-communicate value as well, perhaps 8-10 characters long.
Something like perhaps,
AHS3DJ6BW
B83JS1HSK
(I typed that, so it's not really that random)
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 10; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
You can optimize this by preallocating the $res string and caching the result of strlen($chars)-1. This is left as an exercise to the reader, since probably you won't be generating thousands of coupons per second.
Try this:
substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 10)
Why don't keep it simple?
<?php
echo strtoupper(uniqid());
?>
Always returns 13 character long uppercased random code.
You can use the coupon code generator PHP class file to generate N number of coupons and its customizable, with various options of adding own mask with own prefix and suffix. Simple PHP coupon code generator
Example:
coupon::generate(8); // J5BST6NQ
http://webarto.com/35/php-random-string-generator
Here you go.
function randr($j = 8){
$string = "";
for($i=0;$i < $j;$i++){
srand((double)microtime()*1234567);
$x = mt_rand(0,2);
switch($x){
case 0:$string.= chr(mt_rand(97,122));break;
case 1:$string.= chr(mt_rand(65,90));break;
case 2:$string.= chr(mt_rand(48,57));break;
}
}
return strtoupper($string); //to uppercase
}
If there are no security requirements for these, then you don't really need randomly generated codes. I would just use incremental IDs, such as those generated by whatever RDBMS you use. Optionally, if you have different types of coupons, you could prefix the codes with something, e.g.:
CX00019 QZ0001C
CX0001A QZ0001D
CX0001B QZ0001E
Alternately, you could even use dictionary words in the coupon, as such coupon codes are easier to remember and faster for users to type. Companies like Dreamhost use these for their promo codes, e.g.:
Promo60
NoSetupFee
YELLOWGORILLA82
Some of these are obviously human-created (which you might want to have the option of), but they can also be generated using a dictionary list. But even if they are randomly-generated nonsense phrases, the fact that the characters follow a logical pattern still makes it much more user-friendly than something like R7QZ8A92F1. So I would strongly advise against using the latter type of coupon codes just on the basis that they "look cool". Your customers will thank you.
$size = 12;
$string = strtoupper(substr(md5(time().rand(10000,99999)), 0, $size));
function generateCouponCode($length = 8) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$ret = '';
for($i = 0; $i < $length; ++$i) {
$random = str_shuffle($chars);
$ret .= $random[0];
}
return $ret;
}
you can find a lot of function in php rand manual
http://php.net/manual/en/function.rand.php
i like this one
<?php
//To Pull 8 Unique Random Values Out Of AlphaNumeric
//removed number 0, capital o, number 1 and small L
//Total: keys = 32, elements = 33
$characters = array(
"A","B","C","D","E","F","G","H","J","K","L","M",
"N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9");
//make an "empty container" or array for our keys
$keys = array();
//first count of $keys is empty so "1", remaining count is 1-7 = total 8 times
while(count($keys) < 8) {
//"0" because we use this to FIND ARRAY KEYS which has a 0 value
//"-1" because were only concerned of number of keys which is 32 not 33
//count($characters) = 33
$x = mt_rand(0, count($characters)-1);
if(!in_array($x, $keys)) {
$keys[] = $x;
}
}
foreach($keys as $key){
$random_chars .= $characters[$key];
}
echo $random_chars;
?>
$length = 9;
$code = (strtoupper(substr(md5(time()), 0, $length)));
Just Write
$voucher_no = date('ymd') . rand(1000, 9999);
while(SapItem::where('voucher_no', $voucher_no)->exists()){
$voucher_no = date('ymd') . rand(1000, 9999);
}
Output: 2204171447