PHP string of zeros of random length? - php

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

Related

php loop with letters without using an array of letters

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++;
}
}

Split a string into smaller strings and not arrays

need a little help with a small issue of string splitting.
I'm trying to split a serial number into two, do some calculations on the second half and join it back to the first half. My problem is the second half starts with two zeros and PHP removes the leading zeros.
I think keeping the variables as strings will keep the zeros but I can't seem to find a way to split the serial number into smaller strings, all the methods I try split them into an array. Here is a part of my code;
$info1 = nkw549blc003i00021; //this is the serial number.
I want to split $info1 into;
$number1 = nkw549blc003i0
$number2 = 0021
then use for loop on $number2 like
$num = 1;
for ($num=1; $num < $unitsquantity[$key] ; $num++) {
$sum = $number2+$num;
$final=$number1.$sum;
echo "$final<br>";
}
Any help is greatly appreciated.
$info1 = 'nkw549blc003i00021';
$number1 = substr($info1, 0, -4);
$number2 = sprintf('%1$04d', substr($info1, -4, 4));
If the string will always be 4 chars long, you can use str_pad
for ($num=1; $num < $unitsquantity[$key] ; $num++) {
echo $number1 . str_pad($number2+$num, 4, '0', STR_PAD_LEFT);
}
Strings are array chars, so you can get each char of them by iterating through their length
define('SERIAL_NUM_LEN', 4);
$info1 = 'nkw549blc003i00021';
$number1 = ''; $number2 = '';
for ($i = 0; $i < strlen($info1)-SERIAL_NUM_LEN; $i++) {
$number1 .= $info1[$i];
}
for ($i = strlen($info1)-SERIAL_NUM_LEN; $i < strlen($info1); $i++) {
$number2 .= $info1[$i];
}
var_dump($number1, $number2);
Output:
string 'nkw549blc003i0' (length=14)
string '0021' (length=4)
This way you can skip whichever chars from the string you want if you want to build totally different string. Or add chars in the middle.

PHP: Generating random string with both suffix and prefix as capital letters

Hie guys i want to create a random string of numbers where there is a fixed letter B at the beginning and a set of eight integers ending with any random letter, like for example B07224081A where A and the other numbers are random. This string should be unique. How can I do this?
Do you mean something like this?
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(10000000, 99999999);
$prefix = "B";
$sufix = $letters[rand(0, 25)];
$string = $prefix . $numbers . $sufix;
echo $string; // printed "B74099731P" in my case
The more characters - the greater chance to generate unique string.
I think that's much better method to use uniqid() since it's based on miliseconds. Uniqueness of generated string is guaranteed.
This should work for you.
$randomString = "B";
for ($i = 0; $i < 9; $i++) {
if ($i < 8) {
$randomString.=rand(0,9);
}
if ($i == 8) {
$randomString.=chr(rand(65,90));
}
}
echo $randomString;

PHP loop thru hex numbers from a form POST always gives the first number as 0. why?

i have a form with two text fields, "from" and "to."
when i enter values such as "100000" and "10000F" and do a for loop, it always comes out like:
0 100001 100002 100003 100004 100005 100006 100007 100008 100009 10000a 10000b 10000c 10000d 10000e 10000f
if i plug in the range for the loop manually, i get:
100000 100001 100002 100003 100004 100005 100006 100007 100008 100009 10000a 10000b 10000c 10000d 10000e 10000f
using:
for ($i = '0x'.$_POST['from']; $i <= '0x'.$_POST['to']; $i++) { print dechex($i)."\n"; }
versus:
for ($i = 0x100000; $i <= 0x10000F; $i++) { print dechex($i)."\n"; }
if anyone knows what i am doing wrong here, please let me know.
i have also tried tried adding the "0x" to the numbers via the form with the same results.
thanks!
While $i++ is converting $i to a number, this doesn't run until after the first loop. Apparently dechex doesn't try to interpret strings as numbers and just barfs.
To force conversion, prefix the string expression with a +:
for ($i = +('0x'.$_POST['from']); $i <= '0x'.$_POST['to']; $i++) {
print dechex($i)."\n";
}
Tested and working on PHP 5.2.6.
(Note that casting does not work! (int)('0x100000') returns 0.)
You should use intval() to convert a hex string to a number. dechex() will take the number and turn it back into a hex string:
$from = intval('100001', 16);
$to = intval('10000f', 16);
for ($i = $from; $i <= $to; $i++) {
print dechex($i) . "\n";
}
'0x'.$_POST['from']; is a string $i = 0x100000 is a number
Your first iteration will cast the string value to a number using standard PHP casting (as an integer value to the first non-numeric character, which is the 'x' giving a start value of 0)
You can also do
for ($i = intval('0x'.$_POST['from'], 0); $i <= intval('0x'.$_POST['to'], 0); $i++) { print dechex($i)."\n"; }
You need to convert your hex string to an actual integer first. Something like this function does.
Otherwise, PHP will handle it as a string.

How do I "add" strings in PHP - not concatenate, but "add" them. (as if each character was a base 36 numbers)

Unfortunately I inherited some code (c/c++) that does some string manipulation and now I need to copy/port that over to php so this functionality can be accessed over the internets.
Specifically the functionality takes some arbitrary strings and "adds" them together. (the c code iterates down the character array and then does some checking to make sure they are in the alphanumeric range)
I can't find specific code examples on how to do this (I am not a PHP developer) - can anyone point me to some resources that will explain this? (basically how to do string/character array manipulation)
EDIT
In response to some comments and answers:
I want the result in ascii, but essentially I will be adding base 36 numbers.
The C code right now converts to base 36 (from ascii)
then "adds" each element together (does not carry - although the original author intended that - and it for some strange reason does the "add" from most significant to least)
Then converts back to ascii.
Strings can be of different lengths
Based on the current answers i think I have enough of what I need. It is always frustrating sometimes learning a new language - you know exactly what you want and you can do it in other languages, just not the one that is for the task at hand...
Thanks for the responses so far.
Can't you just base_convert() them?
$sum = base_convert($str1, 36, 10) + base_convert($str2, 36, 10);
$sum36 = base_convert($sum, 10, 36);
Or do you need arbitrary precision? Here's a stab at arbitrary precision addition, in base 36:
function b36_add($str1, $str2)
{
$to10 = array();
for ($i = 0; $i < 36; ++$i)
{
$to10[base_convert($i, 10, 36)] = $i;
}
$len = max(strlen($str1), strlen($str2));
$str1 = str_repeat('0', $len - strlen($str1)) . $str1;
$str2 = str_repeat('0', $len - strlen($str2)) . $str2;
$pos = $len - 1;
$carry = 0;
$sum = '';
do
{
$tmp = base_convert($carry + $to10[$str1[$pos]] + $to10[$str2[$pos]], 10, 36);
$sum .= substr($tmp, -1);
$carry = (int) substr($tmp, 0, -1);
}
while (--$pos >= 0);
$sum = strrev($sum);
if ($carry)
{
$sum = base_convert($carry, 10, 36) . $sum;
}
return $sum;
}
If you have a string like this in php you can just call the index of an individual character like so:
<?
$x = "Hello";
print $x[0] . "\n";
So in other words, $string_var[n] gives you the nth char, 0-indexed.
First off, I'm assuming you want to add ascii values.
ord() might help you. Based on the other answer, something like:
<?php
function addStrings($x, $y){
// Assumes that both strings are the same length
for($i=0; $i<strlen($x); $i++){
$result[i] = ord($x[i]) + ord($y[i]);
}
return $result;
}
?>
If you use this, you'll probably want to do something if $x and $y are different lengths, but I think it gets the idea across.

Categories