php loop with letters without using an array of letters - php

I have an php code that writes an excel file with a variable number of columns. Each 4 rows, on the 5th I want to put the total of the four rows above, per column.
My issue is on how to write the formula in terms of columns.
My code is this one:
$col_index=20;
$i=20;
for($anno = $annoMin; $anno<=$annoMax; $anno++){
for($mese = 1; $mese <= 12; $mese++){
$string = "=$i$v+$i$q-$i$z-$i$t";
$ews->setCellValueByColumnAndRow($col_index,$k,$string);
$col_index=$col_index+1;
$i=$i+1;
}
}
In $string I need to put the column letter instead of $i. $v,$q,$z and $t are the reference to the rows and are ok. In other words $string should be evaluated to:
$string = "=U5+U3-U2-U4";
during the first for loop,
$string = "=V5+V3-V2-V4";
in the second and so on.
I know I can build an array of columns letter and use that $i reference to get my goal but I'm sure there is a better approach. I am using php 5.5 btw
The other option is to write the formula with the R1C1 notation but I'm pretty sure I cannot have the standard and the R1C1 notation in an excel sheet at the same time

You can increment a string variable. I think this is the most efficient way to do what you need (if I understood it right).
$ch = "a";
++$ch;
echo $ch; //prints "b"
Knowing this you can build a loop to update the value as you need.
This works very good for Excel because:
$ch = "z";
++$ch;
echo $ch; //prints aa

I'm just concentrating on the column letter as that seems to be what you're asking. Use the ASCII code of the letter and increment it, then convert it to the character:
$col_index = 20;
$i = ord('U'); // 85
for($anno = $annoMin; $anno<=$annoMax; $anno++){
for($mese = 1; $mese <= 12; $mese++){
$c = chr($i);
$string = "=$c$v+$c$q-$c$z-$c$t"; // $i will be U then V etc...
$ews->setCellValueByColumnAndRow($col_index,$k,$string);
$col_index = $col_index+1;
$i++;
}
}
If you need to keep $i starting at 20 and incrementing then just add 65:
$col_index = 20;
$i = 20;
for($anno = $annoMin; $anno<=$annoMax; $anno++){
for($mese = 1; $mese <= 12; $mese++){
$c = chr($i + 65);
$string = "=$c$v+$c$q-$c$z-$c$t"; // $i will be U then V etc...
$ews->setCellValueByColumnAndRow($col_index,$k,$string);
$col_index = $col_index+1;
$i++;
}
}

Related

Increment letters like number by certain value in php

In php if I writ
$c='A';
$c++;
it increments to 'B' but if I want to increment it with 2 ,3 or more ,
eg: $c+2 or $c+3 ,to get the alternate alphabets
for ($column = 'B'; $column < $highestColumn; $column++) {
$cell = $worksheet->getCell($column.$row);
$cell2=$worksheet->getCell($column+1.$row);
}
but the $column+1 dont work
how to do that ?
Incrementing letters will only work with the ++ incrementor operator, not with + addition.
If you want to continue using an incrementor, you can use a loop:
$column = 'AH';
$step = 7; // number of columns to step by
for($ = 0; $i < $step; $i++) {
$column++;
}
However, PHP's character incrementor won't work backwards, so you couldn't use a negative step value
If you want to use addition rather than a loop, then you need to convert that column to a numeric value, do the addition, then convert back
$column = 'AH';
$step = 7; // number of columns to step by
$columnNumber = PHPExcel_Cell::columnIndexFromString($column) + $step;
$column = PHPExcel_Cell::stringFromColumnIndex($columnNumber - 1);
Which has the added benefit of allowing you to use negative step values
If you want to increment the character by 2, adding won't work.
Try this instead:
echo chr(ord($c) + 2)
Explanation:
Calculate the ascii value of $c using ord($c)
Add the ascii value by 2.
Convert this achii value to string using chr() function.
Refer to ord() and chr() functions.
Note:
As Mark Baker specifies, this will only work to Z and not beyond.

How to increment number after letter in PHP

I'm looking to increment a number after a certain letter.
I have a list of own Ids and i would like to increment it without write it manually each time i add a new id.
$ids = array('303.L1', '303.L2', '303.L3', '303.L4');
so i use the END() function to extract the last id from this array.
this is what i've tried but i cannot get a result.
$i = 0;
while($i <= count($ids)){
$i++;
$new_increment_id = 1;
$final_increment = end($last_id) + $new_increment_id;
}
echo $final_increment;
New method, but it is adding me double dot between number and letter.
$i = 0;
while($i <= count($ids)){
$i++;
$chars = preg_split("/[0-9]+/", end($ids));
$nums = preg_split("/[a-zA-Z]+/", end($ids));
$increment = $nums[1] + 1;
$final_increment = $nums[0].$chars[1].$increment;
}
//i will use this id to be inserted to database as id:
echo $final_increment;
Is there another way to increment the last number after L ?
Any help is appreciated.
If you don't want a predefined list, but you want a defined number of ids returned in an $ids variable u can use the following code
<?php
$i = 0;
$number_of_ids = 4;
$id_prefix = "303.L";
$ids = array();
while($i < $number_of_ids){
$ids[] = $id_prefix . (++$i); // adds prefix and number to array ids.
}
var_dump($ids);
// will output '303.L1', '303.L2', '303.L3', '303.L4'
?>
I'm a bit confused because you say "without write it manually". But I think I have a solution:
$ids = array('303.L1', '303.L2', '303.L3', '303.L4');
$i = 0;
while($i <= count($ids)){
++$i;
//Adding a new item to that array
$ids[] = "303.L" . $i;
}
This would increment just that LAST number, starting at zero. If you wanted to continue where you left off, that'd be simple too. Just take $i = 0; and replace with:
//Grab last item in array
$current_index = $ids[count($ids) - 1];
//Separates the string (i.e. '303.L1') into an array of ['303', '1']
$exploded_id = explode('.L', $current_index);
//Then we just grab the second item in the array (index 1)
$i = $exploded_id[1];

PHP string of zeros of random length?

How do I insert a random string of zeros (length between x and x+y) before each of the four digits for the code snipet below?
an example would be:
$quotes=array("000350.00155.062.00000044");
<?php
$quotes=array("$random+00350.$random2+0155.$random3+062.$random4+044");
Something like this would work, I don't completely understand your array declaration however and may have missed the point.
$quotes = array("00350","0155","062","044");
foreach($quotes as $i => $v) {
$a = rand($x, $x + $y);
$zeros = "";
for($j = 0; $j < $a; $j++) $zeros .= "0";
$quotes[$i] = $zeros . $v;
}
I would run a pseudo random over an uniform distribution [0-1]. Then, ceil of the number would be my number of zeros.
Done! :)
if you only have the $quotes variable I would you suggest you to do this:
-> explode $quotes (using the "explode" function and puting the "." as the delimiter)
-> get a random integer from x to x+y using rand(x, x+y)
-> concatenate the parts using a loop

PHP code for generating decent-looking coupon codes (mix of letters and numbers)

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

Wrongly asked or am I stupid?

There's a blog post comment on codinghorror.com by Paul Jungwirth which includes a little programming task:
You have the numbers 123456789, in that order. Between each number, you must insert either nothing, a plus sign, or a multiplication sign, so that the resulting expression equals 2001. Write a program that prints all solutions. (There are two.)
Bored, I thought, I'd have a go, but I'll be damned if I can get a result for 2001. I think the code below is sound and I reckon that there are zero solutions that result in 2001. According to my code, there are two solutions for 2002. Am I right or am I wrong?
/**
* Take the numbers 123456789 and form expressions by inserting one of ''
* (empty string), '+' or '*' between each number.
* Find (2) solutions such that the expression evaluates to the number 2001
*/
$input = array(1,2,3,4,5,6,7,8,9);
// an array of strings representing 8 digit, base 3 numbers
$ops = array();
$numOps = sizeof($input)-1; // always 8
$mask = str_repeat('0', $numOps); // mask of 8 zeros for padding
// generate the ops array
$limit = pow(3, $numOps) -1;
for ($i = 0; $i <= $limit; $i++) {
$s = (string) $i;
$s = base_convert($s, 10, 3);
$ops[] = substr($mask, 0, $numOps - strlen($s)) . $s;
}
// for each element in the ops array, generate an expression by inserting
// '', '*' or '+' between the numbers in $input. e.g. element 11111111 will
// result in 1+2+3+4+5+6+7+8+9
$limit = sizeof($ops);
$stringResult = null;
$numericResult = null;
for ($i = 0; $i < $limit; $i++) {
$l = $numOps;
$stringResult = '';
$numericResult = 0;
for ($j = 0; $j <= $l; $j++) {
$stringResult .= (string) $input[$j];
switch (substr($ops[$i], $j, 1)) {
case '0':
break;
case '1':
$stringResult .= '+';
break;
case '2':
$stringResult .= '*';
break;
default :
}
}
// evaluate the expression
// split the expression into smaller ones to be added together
$temp = explode('+', $stringResult);
$additionElems = array();
foreach ($temp as $subExpressions)
{
// split each of those into ones to be multiplied together
$multplicationElems = explode('*', $subExpressions);
$working = 1;
foreach ($multplicationElems as $operand) {
$working *= $operand;
}
$additionElems[] = $working;
}
$numericResult = 0;
foreach($additionElems as $operand)
{
$numericResult += $operand;
}
if ($numericResult == 2001) {
echo "{$stringResult}\n";
}
}
Further down the same page you linked to.... =)
"Paul Jungwirth wrote:
You have the numbers 123456789, in
that order. Between each number, you
must insert either nothing, a plus
sign, or a multiplication sign, so
that the resulting expression equals
2001. Write a program that prints all solutions. (There are two.)
I think you meant 2002, not 2001. :)
(Just correcting for anyone else like
me who obsessively tries to solve
little "practice" problems like this
one, and then hit Google when their
result doesn't match the stated
answer. ;) Damn, some of those Perl
examples are ugly.)"
The number is 2002.
Recursive solution takes eleven lines of JavaScript (excluding string expression evaluation, which is a standard JavaScript function, however it would probably take another ten or so lines of code to roll your own for this specific scenario):
function combine (digit,exp) {
if (digit > 9) {
if (eval(exp) == 2002) alert(exp+'=2002');
return;
}
combine(digit+1,exp+'+'+digit);
combine(digit+1,exp+'*'+digit);
combine(digit+1,exp+digit);
return;
}
combine(2,'1');

Categories