i'm working on a project that will need to have everything shown with barcodes, so I've generated 7 numbers for EAN8 algorithm and now have to get these 7 numbers seperately, right now i'm using for the generation
$codeint = mt_rand(1000000, 9999999);
and I need to get this 7 numbers each seperately so I can calculate the checksum for EAN8, how can i split this integer to 7 parts, for example
12345678 to
arr[0]=1
arr[1]=2
arr[2]=3
arr[3]=4
arr[4]=5
arr[5]=6
arr[6]=7
any help would be appreciated..
also I think that I'm becoming crazy :D because I already tried most of the solutions you gave me here before and something is not working like it should work, for example:
$codeint = mt_rand(1000000, 9999999);
echo $codeint."c</br>";
echo $codeint[1];
echo $codeint[2];
echo $codeint[3];
gives me :
9082573c
empty row
empty row
empty row
solved! $codeint = (string)(mt_rand(1000000, 9999999));
Try to use str_split() function:
$var = 1234567;
print_r(str_split($var));
Result:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
There are two ways to do this, one of which is reasonably unique to PHP:
1) In PHP, you can treat an integer value as a string and then index into the individual digits:
$digits = "$codeint";
// access a digit using intval($digits[3])
2) However, the much more elegant way is to use actual integer division and a little knowledge about mathematical identities of digits, namely in a number 123, each place value is composed of ascending powers of 10, i.e.: 1 * 10^2 + 2 * 10^1 + 3 * 10^0.
Consequently, dividing by powers of 10 will permit you to access each digit in turn.
it's basic math you can divide them in loop by 10
12345678 is 8*10^1 + 7*10^2 + 6*10^3...
the other option is cast it to char array and then just get it as char
Edit
After #HamZa DzCyberDeV suggestion
$string = '12345678';
echo "<pre>"; print_r (str_split($string));
But in mind it comes like below but your suggestion is better one.
If you're getting string from your function then you can use below one
$string = '12345678';
$arr = explode(",", chunk_split($string, 1, ','));
$len = count($arr);
unset($arr[$len-1]);
echo "<pre>";
print_r($arr);
and output is
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
)
okay what you can do is
Type cast to string with prefill 0
this is how it works
$sinteger = (string)$integer;
$arrsize = 0 ;
for (i=strlen($sinteger), i == 0 ; i--)
{
arr[$arrsize]=$sinteger[i];
$arrsize++;
}
And then what is left you can prefill with zip.
I am sure you can manage the order reverse or previous. but this is simple approach.
Related
I'm wanting to replace the first character of a string with a specific character depending on its value,
A = 0
B = 1
C = 2
Is there a way to do this based on rules? In total I will have 8 rules.
Ok, so I'm editing this to add more information as I don't think some people understand / want to help without the full picture...
My string will be any length between 5 and 10 characters
Capitals will not factor into this, it is not case sensitive
Currently there is no code, I'm not sure the best way to do this. I can write an if statement on a substring, but I know straight away that is inefficient.
Below is the before and after that I am expecting, I have kept these examples simple but all I am looking to do is replace the first character with a specific character depending on its value. For now, there are eight rules, but this could grow in the future
INPUT OUTPUT
ANDREW 1NDREW
BRIAN 2RIAN
BOBBY 2OBBY
CRAIG 3RAIG
DAVID 4AVID
DUNCAN 4UNCAN
EDDIE 5DDIE
FRANK 6RANK
GEOFF 7EOFF
GIANA 7IANA
HAYLEY 8AYLEY
So as you can see, pretty straight forward, but is there a simple way to specifically specify what a character should be replaced by?
Assuming all the rules are for single characters, like in the example, it would be easisest to code them in to a dictionary:
$rules = array('A' => 0, 'B' => 0 /* etc... */);
$str[0] = $rules[$str[0]];
I think this is what you want.
<?php
$input = array('ANDREW','BRIAN','BOBBY','CRAIG','DAVID','DUNCAN','EDDIE','FRANK','GEOFF','GIANA','HAYLEY');
$array = range('A','Z');
$array = array_flip(array_filter(array_merge(array(0), $array)));
$output = [];
foreach($input as $k=>$v){
$output[] = $array[$v[0]].substr($v, 1);
}
print_r($output);
?>
Output:
Array (
[0] => 1NDREW
[1] => 2RIAN
[2] => 2OBBY
[3] => 3RAIG
[4] => 4AVID
[5] => 4UNCAN
[6] => 5DDIE
[7] => 6RANK
[8] => 7EOFF
[9] => 7IANA
[10] => 8AYLEY
)
DEMO: https://3v4l.org/BHLPk
If I have a string as : 10 20 3 4 15 6
How can I convert it to individual numbers and store it in a array?
PHP is very clever when dealing with types of variables. You don't need it to be an integer, it can be a string of numbers, and PHP would still treat it as integers when performing operations on them.
If you want to have each element be the numbers separated by spaces, you simply do
$array = explode(" ", "10 20 3 4 15 6");
The output of $array would then be
Array (
[0] => 10
[1] => 20
[2] => 3
[3] => 4
[4] => 15
[6] => 6
)
Live demo
$str = "10 20 3 4 15 6";
$arr = str_split($str);
$intArr = array_map('intval', $arr);
Might be a better way of doing it but the above should do the work.
I've been trying for the couple of days to split a string into letters and numbers. I've found various solutions but they do not work up to my expectations (some of them only separate letters from digits (not integers or float numbers/per say negative numbers).
Here's an example:
$input = '-4D-3A'; // edit: the TEXT part can have multiple chars, i.e. -4AB-3A-5SD
$result = preg_split('/(?<=\d)(?=[a-z])|(?<=[a-z])(?=\d)/i', $input);
print_r($result);
Result:
Array ( [0] => -4 [1] => D-3 [2] => A )
And I need it to be [0] => -4 [1] => D [2] => -3 [3] => A
I've tried doing several changes but no result so far, could you please help me if possible?
Thank you.
try this:
$input = '-4D-3A';
$result = preg_split('/(-?[0-9]+\.?[0-9]*)/i', $input, 0, PREG_SPLIT_DELIM_CAPTURE);
$result=array_filter($result);
print_r($result);
It will split by numbers BUT also capture the delimiter (number)
giving : Array ( [1] => -4 [4] => D [5] => -3 [8] => A )
I've patterened number as:
1. has optional negative sign (you may want to do + too)
2. followed by one or more digits
3. followed by an optional decimal point
4. followed by zero or more digits
Can anyone point out the solution to "-0." being valid number?
How about this regex? ([-]{,1}\d+|[a-zA-Z]+)
I tested it out on http://www.rubular.com/ seems to work as you want.
I have some bar code numbers in an array. PHP seems to be rounding the barcodes which start with leading zeros. How do I stop this happening and keep the numbers as they were? Code I am using is below:
$array = array(5032227448124,5060028999989,5010121096504,5060028999996,5016254104864,5016402052788,8422248036986,0000003798720,0000003735503,0000003798713);
echo '<pre>';
print_r($array);
echo '</pre>';
This echos the following, as you can see the last four bar codes which feature leading zeros have been changed and had their leading zeros removed. These numbers are always 13 digits long and are padded with zeros.
Array
(
[0] => 5032227448124
[1] => 5060028999989
[2] => 5010121096504
[3] => 5060028999996
[4] => 5016254104864
[5] => 5016402052788
[6] => 8422248036986
[7] => 31
[8] => 1030979
[9] => 31
[10] => 1031004
)
You need to quote them as strings if they arent a number (integer, float, exponent).
The obvious, easy, and also likely wrong answer is to make them strings.
The better answer is to use printf()/sprintf() to pad with zeroes:
printf('%013d', 12345); // output: 0000000012345
MySQL also has a handy LPAD() function:
SELECT LPAD(12345, 13, 0) // output 0000000012345
Here's an easy way to convert your values to padded strings:
$array = array_map(function ($e){return str_pad($e, 13, "0", STR_PAD_LEFT);}, $array);
In the end I just needed to put double quotes around each barcode number e.g.
$array = array("5032227448124","5060028999989","5010121096504","5060028999996","5016254104864","5016402052788","8422248036986","0000003798720","0000003735503","0000003798713");
I just saw this on php.net description of how key to value mapping works:
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
I just cant quite understand how 11 could be assigned key 6. I know 5 is not possible since it is already used on the second element as a key so it makes sense to jump it over.
But should not be 11 intuitively assigned key 4 in the first place since the first element of the array 10 is assigned key 0 and therefore the key value is incremented 0..1..2..3..4 from that point according to the first index unless specified otherwise (e.g 5=>6 could have had key 1, 3=>7 with key 2, and 'a'=> 4 could have had key 3 if not specified)? And also, why does it say that 11 should be assigned a key that represents the maximum integer of indices (in this case 6 since 5 was used already)?
Would appreciate any help/clarification. Please let me know if the question needs to be clarified. Thanks much.
It is implemented in this way just because it is the most performant solution - to just use maximum_specified_key + 1, rather than to find a hole in enumration
I believe it has to do with the way that PHP arrays work. Each has an internal cursor for the each, current, next, pos and similar methods. My guess: as a new key is specified, if it is higher than the current cursor, the cursor is advanced to that position so that anything added after that point will still be at current position + 1.
And also, why does it say that 11
should be assigned a key that
represents the maximum integer of
indices (in this case 6 since 5 was
used already)?
Why not? As zerkms says, it's performant, so there's that.
It's also more or less what you might expect. Given an array with mixed keys like that, what would you expect array_push() to do?
Of course, if you're running into this kind of thing in real life, it's probably time to stop and consider some amount of refactoring. Arrays in PHP are very flexible, and these somewhat arbitrary decisions had to be made. They're documented. The only alternative is to make array usage much more rigid.
The PHP manual gives you the answer in the link you provided:
As mentioned above, if no key is specified, the maximum of the
existing integer indices is taken, and the new key will be that
maximum value plus 1 (but at least 0). If no integer indices exist
yet, the key will be 0 (zero).
The code:
$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (maximum of integer-indices was 5)
'8' => 2, // key = 8 (integer!)
'02' => 77, // key = '02'
0 => 12 // the value 10 will be overwritten by 12
);
So far the maximum key when you get to 'a' is 5 so the next available key according to the php manual would be 5 + 1 i.e. 6.
Note that the maximum integer key used
for this need not currently exist in the array. It need only have
existed in the array at some time since the last time the array was
re-indexed.
// empty the array;
foreach( $switching as $key => $value ) {
unset( $switching[$key] );
}
// refill it with new elements
for( $i = 0; $i < 10; $i++ ) {
$switching[] = $i + 1;
}
output array:
Array
(
[9] => 1
[10] => 2
[11] => 3
[12] => 4
[13] => 5
[14] => 6
[15] => 7
[16] => 8
[17] => 9
[18] => 10
)