I'm hoping someone out there can see what I'm missing in using PHP's "substr" to get two halves of a 40 character string:
What I have is variable $dk that's 40 chars long. I've verified the variable's there with an echo statement and it's returning the right value. I've verified the "gkgk" = 1 or 2 as well. But I'm getting nothing as a result. Why?
$dk = "1234567891123456789212345678931234567894";
echo "<br><br>DK = ".$dk."<br><br>";
if ($a == 1) {
echo "A = 1<br><br>";
$gk = substr($dk, 0, 20); //I'm expecting the first 20 chars...12345678911234567892
} else {
echo "A = 2<br><br>";
$gk = substr($dk, 20, 20); //expecting the last 20 chars...12345678931234567894
}
echo "GK = ".$gk;
I tried putting the variable in quotes, just in case it was a syntax issue. All I get is
DK =1234567891123456789212345678931234567894
A = 1
GK =
No clue what's going wrong. I hope I've given enough explanation and my code so people can understand! Thank you for any help.
Code is correct but if you are checking $a is one or two, first of all u must add value to $a variable.
above of this ---> if ($a == 1) { <-------- add this $a=1;
or
above of this ---> if ($a == 1) { <-------- add this $a=2;
Related
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
I have a comma delimited list of numbers which i am converting into an array and what i want to know about the list of numbers is if the numbers listed obey a natural ordering of numbers,you know,have a difference of exactly 1 between the next and the previous.
If its true the list obeys the natural ordering,i want to pick the first number of the list and if not the list obeys not the natural order,i pick the second.
This is my code.
<?php
error_reporting(0);
/**
Analyze numbers
Condition 1
if from number to the next has a difference of 1,then pick the first number in the list
Condition 2
if from one number the next,a difference of greater than 1 was found,then pick next from first
Condition 3
if list contains only one number,pick the number
*/
$number_picked = null;
$a = '5,7,8,9,10';
$b = '2,3,4,5,6,7,8,9,10';
$c = '10';
$data = explode(',', $b);
$count = count($data);
foreach($data as $index => $number)
{
/**
If array has exactly one value
*/
if($count == 1){
echo 'number is:'.$number;
exit();
}
$previous = $data[($count+$index-1) % $count];
$current = $number;
$next = $data[($index+1) % $count];
$diff = ($next - $previous);
if($diff == 1){
$number_picked = array_values($data)[0];
echo $number_picked.'correct';
}
elseif($diff > 1){
$number_picked = array_values($data)[1];
echo $number_picked.'wrong';
}
}
?>
The problem i am having is to figure out how to test the difference for all array elements.
No loops are needed, a little bit of maths will help you here. Once you have your numbers in an array:
$a = explode(',', '5,7,8,9,10');
pass them to this function:-
function isSequential(array $sequence, $diff = 1)
{
return $sequence[count($sequence) - 1] === $sequence[0] + ($diff * (count($sequence) - 1));
}
The function will return true if the numbers in the array follow a natural sequence. You should even be able to adjust it for different spacings between numbers, eg 2, 4, 6, 8, etc using the $diff parameter, although I haven't tested that thoroughly.
See it working.
Keep in mind that this will only work if your list of numbers is ordered from smallest to largest.
Try using a function to solve this... Like so:
<?php
error_reporting(0);
/**
Analyze numbers
Condition 1
if from number to the next has a difference of 1,then pick the first number in the list
Condition 2
if from one number the next,a difference of greater than 1 was found,then pick next from first
Condition 3
if list contains only one number,pick the number
*/
$number_picked = null;
$a = '5,7,8,9,10';
$b = '2,3,4,5,6,7,8,9,10';
$c = '10';
function test($string) {
$data = explode(',', $string);
if(count($data) === 1){
return 'number is:'.$number;
}
foreach($data as $index => $number)
{
$previous = $data[($count+$index-1) % $count];
$current = $number;
$next = $data[($index+1) % $count];
$diff = ($next - $previous);
if($diff == 1){
$number_picked = array_values($data)[0];
return $number_picked.'correct';
}
elseif($diff > 1){
$number_picked = array_values($data)[1];
return $number_picked.'wrong';
}
}
}
echo test($a);
echo test($b);
echo test($c);
?>
You already know how to explode the list, so I'll skip that.
You already handle a single item, so I'll skip that as well.
What is left, is checking the rest of the array. Basically; there's two possible outcome values: either the first element or the second. So we'll save those two first:
$outcome1 = $list[0];
$outcome2 = $list[1];
Next, we'll loop over the items. We'll remember the last found item, and make sure that the difference between the new and the old is 1. If it is, we continue. If it isn't, we abort and immediately return $outcome2.
If we reach the end of the list without aborting, it's naturally ordered, so we return $outcome1.
$lastNumber = null;
foreach( $items as $number ) {
if($lastNumber === null || $number - $lastNumber == 1 ) {
// continue scanning
$lastNumber = $number;
}
else {
// not ordened
return $outcome2;
}
}
return $outcome1; // scanned everything; was ordened.
(Note: code not tested)
To avoid the headache of accessing the previous or next element, and deciding whether it still is inside the array or not, use the fact that on a natural ordering the item i and the first item have a difference of i.
Also the corner case you call condition 3 is easier to handle outside the loop than inside of it. But easier still, the way we characterize a natural ordered list holds for a 1-item list :
$natural = true;
for($i=1; $i<$count && $natural; $i++)
$natural &= ($data[$i] == $data[0] + $i)
$number = $natural ? $data[0] : $data[1];
For $count == 1 the loop is never entered and thus $natural stays true : you select the first element.
I have checked a bunch of posts on stackoverflow and on articles on google but none of them were able to answer my question. Here is my code (i've simplified it instead of posting my code)
$first = 10;
$second = 0; //comes from db row count
$total = !is_int($first/$second) ? 0 : $first/$second;
problem is when i do this I keep getting the Division by zero error. I have a bunch and $second isnt always 0, it can be any number. But it does come out to 0 since the row counts for whatever query it comes out as 0. Is there a safe way of checking to see if $first can be divided by $second without giving an error? I have tried # before the !is_int and that just breaks all other statements.
Try this:
$total = ($second == 0) ? 0 : $first / $second;
You can't divide by 0 it is undefined. If you want to handle division by 0 just check if the divisor isn't equals to 0. Or a safer way, chack if it is a positive integer:
$first = 10;
$dbRowCount = dbFunction();
if ($dbRowCount > 0) {
$total = $first / $dbRowCount;
} else {
//Error handling
}
The ternary structure can accept more than one condition. and it will work just as any other if condition, and won't try the second condition if the first fails.
So, just add it
$total = ($first!==0 && $second!==0 && !is_int($first/$second)) ? 0 : $first/$second;
You might want to try checking if your $Second variable is 0.
Something like:
$First = 10;
$Second = $row['table_column'];
if ($Second == 0) {
echo "Oops this will be an error";
}
else
$First/$second = $me;
everybody!
I'm new on Python and I'm using version 3.
I already program in PHP and I have done a script where I enter a string (a name like 'John') and the script returns the number associated to this name, based on a calculation from ASCii table.
The formula is => (ASCii code - 65)%9+1.
Here's my script in PHP:
<?php
$entry=strtoupper("Jack");
$value = 0;
for ($i = 0; $i < strlen($entry); $i++) {
if ($entry[$i] >= "A" && $entry[$i] <= "Z") {
$temp = (ord($entry[$i]) - 65)%9 + 1;
$value += $temp;
}
}
$result = $value%9;
if ($result == 0) $result = 9;
echo $result;
?>
The above result should be 7.
Here's my script in Python:
entry = input("Type your name: ")
name = entry.upper()
value = 0
for letter in range(len(name)):
while letter:
temp = int(ord(name[letter])-65)%9+1
value += temp
result = value%9
if result == 0:
result = 9
print(result)
Well, it's not working, because it seems that Python doesn't run through letters the same way I did in PHP on the first IF statement I used.
Does anybody know how can I solve this?
Thanks in advance!!!
God bless you all!
There are a few problems with your python code.
The biggest one is the if from php somehow becoming a while(and an infinite one) in python.
The direct translation to python would be(and it should make the code work):
if 'A' <= name[letter] <= 'Z':
But, you should never loop through indices in python.
Instead, loop directly over the values you want to work with.
Instead of:
for i in range(len(some_list)):
# do stuff with some_list[i]
You should do:
for item in some_list:
# do stuf with item
Edit:
This is how the loop would look written in a more pythonic way:
for letter in name:
if 'A' <= letter <= 'Z':
value += (ord(letter) - 65) % 9 + 1
Also, you can see here that the int() call and the temp variable are not really needed.
For my latest project I need to shorten the URLs which I then put in a mysql database.
I now ran against a problem, because I don't know how to solve this. Basically, the shortened strings should look like this (I want to include lowercase letters, uppercase letters and numbers)
a
b
...
z
0
...
9
A
...
Z
aa
ab
ac
...
ba
So, 1. URl --> a. Stored in mysql.
Next time, a new url gets stored to --> b because a is already in the mysql database.
And that is it. But I don't have any idea. Could someone of you please help me out?
Edit: Formattted & Further explanation.
It is kinda like the imgur.com URL shortening service. It should continue like this until infinity (which is not needed, I think...)
You can use the following function (code adapted from my personal framework):
function Base($input, $output, $number = 1, $charset = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
if (strlen($charset) >= 2)
{
$input = max(2, min(intval($input), strlen($charset)));
$output = max(2, min(intval($output), strlen($charset)));
$number = ltrim(preg_replace('~[^' . preg_quote(substr($charset, 0, max($input, $output)), '~') . ']+~', '', $number), $charset[0]);
if (strlen($number) > 0)
{
if ($input != 10)
{
$result = 0;
foreach (str_split(strrev($number)) as $key => $value)
{
$result += pow($input, $key) * intval(strpos($charset, $value));
}
$number = $result;
}
if ($output != 10)
{
$result = $charset[$number % $output];
while (($number = intval($number / $output)) > 0)
{
$result = $charset[$number % $output] . $result;
}
$number = $result;
}
return $number;
}
return $charset[0];
}
return false;
}
Basically you just need to grab the newly generated auto-incremented ID (this also makes sure you don't generate any collisions) from your table and pass it to this function like this:
$short_id = Base(10, 62, $auto_increment_id);
Note that the first and second arguments define the input and output bases, respectively.
Also, I've reordered the charset from the "default" 0-9a-zA-Z to comply with your examples.
You can also just use base_convert() if you can live without the mixed alphabet case (base 36).