Substr not allowing double digit codes to process on form - php

I have an array that uses two codes in a list and pushes them into a form on the next page. Currently I have:
$code= array();
$code['c1'] = substr($part, 0, 1);
$code['c2'] = substr($part, 2);
Now, If I select anything with a single digit c1 and single or double c2 then it adds to the form.
Examples:
1-9
1-15
9-12
9-9
But if I try to add anything with double digits in c1 it doesn't add, like:
10-1
10-2
10-11
If I try
$codes= array();
$codes['c1'] = substr($part, 0, 2);
$codes['c2'] = substr($part, 2);
Then no codes show up.
How can I account for both?
UPDATE:
Currently, the above code, if I select 10-58, will dump c1 as 1 and c2 as -5

You can easily use explode() and list() to split any combination of codes...
$part = "1-15";
$codes = array();
list($codes['c1'], $codes['c2']) = explode("-", $part);
print_r($codes);
gives...
Array
(
[c1] => 1
[c2] => 15
)
For
$part = "10-15";
it gives...
Array
(
[c1] => 10
[c2] => 15
)
If you are unsure if your data is always correct, you can check that the data has 2 components after using explode() and only convert it then, you can also do something to report and error or whatever you need...
$split = explode("-", $part);
if ( count($split) == 2 ){
$codes['c1'] = $split[0];
$codes['c2'] = $split[1];
}
else {
// Not of correct format.
}
print_r($codes);

Related

php - add comma thousands separator but remove trailing zeros

I am trying to use PHP to format a number to
Remove all trailing zeros
Add a comma for the thousands separator
List two decimal points, assuming that they are not zeros
I tried this, but its not doing exactly what I am trying to achieve:
$prices[$title]['reg_price'] = (float)number_format($membership->sell_price, 2, ".", "");
$prices[$title]['three_year_price'] = (float)number_format($membership->attributes[$aid]->options[$three_year_oid]->price, 2, ".", "");
I had found that I could strip trailing zeros by casting the number to a float. However, I found that I needed to tell number_format NOT to use the thousands comma separator, because otherwise, when casting 1,500.00 to a float, the result was 1.
So, in summary, I want my code to change 1500.00 to 1,500, 150.00 to 150, and 19.99 to 19.99. How can I make this happen?
function parseCurrency($value) {
if ( intval($value) == $value ) {
$return = number_format($value, 0, ".", ",");
}
else {
$return = number_format($value, 2, ".", ",");
/*
If you don't want to remove trailing zeros from decimals,
eg. 19.90 to become: 19.9, remove the next line
*/
$return = rtrim($return, 0);
}
return $return;
}
$prices[] = parseCurrency(1500.00);
$prices[] = parseCurrency(1500.10);
$prices[] = parseCurrency(1500.1);
$prices[] = parseCurrency(1500);
$prices[] = parseCurrency(123.53);
$prices[] = parseCurrency(1224323.53);
$prices[] = parseCurrency(19.99);
print_r($prices);
Outputs:
Array
(
[0] => 1,500
[1] => 1,500.1
[2] => 1,500.1
[3] => 1,500
[4] => 123.53
[5] => 1,224,323.53
[6] => 19.99
)
This inserts commas, rounds to 2 decimal places, removes trailing zeroes, and removes trailing '.':
rtrim(rtrim(number_format($value,2),0),'.')
You can use the
ltrim($var, '0');
to remove the leading 0. And
rtrim($var, '0');
to remove the trailing.
For replacing "." to "," u can use a function :
function replace_dot($value) {
$str = str_replace('.', ',', $value);
return $str;
}

Put number separately in array

I would like to put a number separately in an array
ex.
$num = 345;
should be in an array so i can call the numbers as
$num[1] (which should return 4)
I tried str_split($num,1) but without succes.
Thanks
EDIT -------
After some more research str_split($num,1) actually did the trick.
(thanks, Crayon Violent)
$num = 345;
$arr1 = str_split($num); print_r($arr1); //Array ( [0] => 3 1 => 4
[2] => 5 )
echo $arr11; //4
str-split
If you are just trying to get individual characters from the string, use substr.
$second_digit = substr( $num, 1, 1 );
while ($num >0) {
$arr[i] = $num %10;
$num = $num/10;
i++
}
//this leaves the array in reverse order i.e. 543
//to flip
array_reverse($arr);

How do I compare a huge amount of strings against the beginning of another?

I have two tables. One with a load of numbers. I then have another table with a list of prefixes( 30, 000+ ).
I need to loop through the prefixes and see if any of the numbers in table 1 starts with any of the prefixes.
This is what I have so far.
$tdata = $r->get_t_data(); //array of prefix
/*
Array
(
[0] => Array
(
[prefix] => 101
[dest] => UK
)
)
*/
$cdata = $r->get_c_data(); //array of number
/*Array
(
[0] => Array
(
[row] => 1
[num] => 441143610120
)
)*/
$temp = array();
$i=0;
$time=0;
foreach ($cdata as $ckey => $c) {
foreach ($tdata as $tkey => $t) {
$length = strlen($t['prefix']);
if (strpos($c['num'], $t['prefix'], 0, $length )) {
$temp[$i]['row']=$c['row'];
$temp[$i]['prefix']=$t['prefix'];
$temp[$i]['dialled']=$c['num'];
$temp[$i]['dest']=$t['dest'];
break;
$i++; //increment only if found
}
}
$time++;
}
so basically it loops through the numbers and then I try and match the first part of the number with the prefix.
At the moment it is returning and empty array.
Hope you can help
The best thing to do is to do the join in your sql as opposed to checking after in your PHP. To do a join with a like you can do this:
SELECT * FROM table t JOIN prefixTable p ON t.num LIKE CONCAT(p.prefix, '%')
The key is LIKE CONCAT(p.prefix, '%') that's saying combine the tables where t.num is like prefix%and in MySQL % is a wildcard since we didn't put a wild card at the front that means that the t.num column has to START with prefix
Your condition if (strpos($c['num'], $t['prefix'], 0, $length )) can return 0, which php will interpret as false. strpos should be checked like this:
if (false !== strpos($c['num'], $t['prefix'], 0, $length )) {}
use preg_grep to reduce the amount of looping/search code you have:
foreach ($table1 as $search) {
$safe_search = preg_quote($search);
$matches = preg_grep("/^$safe_search/", $prefix_array);
if (count($matches) > 0) {
echo "Found $search in the prefix array\n";
}
}

Need Help in building a logic

I need to get all the positions of a character in a string in a form of an array. I know about the php function strpos() but it does not accept an array as an argument.
This is required:
$name = "australia"; //string that needs to be searched
$positions_to_find_for = "a"; // Find all positions of character "a" in an array
$positions_array = [0,5,8]; // This should be the output that says character "a" comes at positions 0, 5 and 8 in string "australia"
Question: What Loops can help me build a function that can help me achieve the required output?
You can use a for to loop that string:
$name = "australia";
$container = array();
$search = 'a';
for($i=0; $i<strlen($name); $i++){
if($name[$i] == $search) $container[] = $i;
}
print_r($container);
/*
Array
(
[0] => 0
[1] => 5
[2] => 8
)
*/
Codepad Example
No loops necessary
$str = 'australia';
$letter='a';
$letterPositions = array_keys(
array_intersect(
str_split($str),
array($letter)
)
);
var_dump($letterPositions);

Most efficient way to delimit key

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow.
Use str_split():
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
The output:
Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
Then of course to insert hyphens between the sets you just implode() them together:
echo implode('-', $sets); // echoes '0123-4567-8901-2345'
If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:
preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');
If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.
This is a bit more general:
<?php
// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
$n = func_num_args();
$str = func_get_arg(0);
$ret = array();
if ($n >= 2) {
for($i=1, $offs=0; $i<$n; ++$i) {
$chars = abs( func_get_arg($i) );
$ret[] = substr($str, $offs, $chars);
$offs += $chars;
}
}
return $ret;
}
echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );
?>

Categories