filling an array with array_pad - php

I am currently working on a site where I have an array that must contain 8 values.
I generate a random number and write it into my array, after that i would liek to check if this number was infact 8 character long. If this was not the case it should be filled with leading zero's.
Here is the code i am using
$number=rand(0,255);
// convert the number to binary and store it as an array
$states=str_split(decbin($number),1);
echo '<pre>'.print_r($states,true).'</pre>';
// in case the number is not 8 bit long make it an 8 bit number using array_pad
if(count($states)<8){
$states = array_pad($states,count($states)-8,"0");
}
The problem is now that it never fills up the array even if the array only consists of 3 or 4 entrys.
Thanks for the help.
Edit :Thanks to everyone for awnsering so quickly the solution provided by Suresh Kamrushi is working.

instead of
$states = array_pad($states,count($states)-8,"0");
Try like this:
$number=rand(0,255);
// convert the number to binary and store it as an array
$states=str_split(decbin($number),1);
echo '<pre>'.print_r($states,true).'</pre>';
// in case the number is not 8 bit long make it an 8 bit number using array_pad
if(count($states)<8){
$states = array_pad($states,8,"0");
}
print_r($states);
PHP fiddle: http://phpfiddle.org/main/code/a1d-m97

If I understand correctly you don't need count($states) - 8:
$states = array_pad($states, -8, "0");
Which will pad the array to a size of 8, with leading zeroes

For array_pad the second argument is the size you want the array to be, not the number of items you want to add to it.
So just do:
if(count($states)<8){
$states = array_pad($states,8,"0");
}
Or, as array_pad has no effect if your array is already big enough, you don't even need the if(count($states)<8) part.

Related

Generate random number with a certain prefix what am i doing wrong

I've been playing about with the uniqid but it started giving me the 13 long string.
I'm looking for a prefix of 100 with up to 6 random numbers afterwards
thanks any help appreciated
function generate_order(){
$order_ref="";
$a=uniqid(prefix,100);
$num4=array('0','1','2','3','4','5','6','7','8','9');
$num=rand(0,9);
$num2=rand(0,9);
$num3=rand(0,9);
shuffle($num4);
//now the final
$order_ref = $num4[0].$num4[3].$num.$num4[1].$num2.$num4[2].$num3.$num4[4];
}
I've got some remakrs to the code above:
Why are you doing a shuffle() on an array with numbers ranging from 1 to 9? This is the same as doing rand(1,9)
Taking point one into account, using rand(10000000, 99999999) will give you the same result.
$a=uniqid(prefix,100) is not used in your function
The prefix in uniqid() should be a string.
Your function doesn't return. You should use return $order_ref;
Hope these will help you fix your function.
In response to your comment
$order_ref = '100'.rand(100000, 999999);
Additional suggestions
If you are planning to use this as an order reference as I suspect, I do not recommand just using random numbers. This will give you a big chance of having duplicate numbers.
Instead, I suggest using $order_ref = '100'.date('u').rand(10, 99);. This will give you a random number based on the current time and thus prevent (or at least minimize) the chance of duplicate order references.
If you want 100 before your result, then use the prefix to enter your desired string
Using uniqid(100) should give you the desired result.
Here is how I would do
1. Define your prefix
2. Generate random number
3. Concat both
$prefix="some_prefix";
$rand_no = rand(1,100);
$rand_no_with_prefix = $prefix.$rand_no;
You can Google for exact syntax and functions.
This is just basic logic I would follow.
Hope it helps.
Also step 4 would be to parse if required(if concated random number needs to be integer)

Getting every combination of X numbers given Y numbers?

I've come to a mathematical problem which for I can't program the logic.
Let me explain it with an example:
Let's say I have 4 holes and 3 marbles, the holes are in order and my marbles are A,B and C and also in order.
I need to get every posible ORDERED combination:
ABC4
AB3C
A2BC
1ABC
This is very simple, but what if the number of holes changes? Let's say now I have 5 holes.
ABC45
AB3C5
A2BC5
1ABC5
AB34C
A2B4C
1AB4C
A23BC
1A3BC
12ABC
Now let's say we have 5 holes and 4 marbles.
ABCD5
ABC4D
AB3CD
A2BCD
1ABCD
And this can be any number of holes and any number of marbles.
The number of combinations is given by:
$combinations = factorial($number_of_holes)/(factorial($number_of_marbles)*factorial($number_of_holes-$number_of_marbles)))
(Here it is the factorial function in case you need it)
function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * factorial($number-1));
}
}
What I need and can't figure out how to program, is a function or a loop or something, that returns an array with the position of the holes, given X numbers of holes and Y number of marbles.
For first example it would be: [[4],[3],[2],[1]], for second: [[4,5],[2,5],[1,5],[3,4],[2,4],[1,5],[2,3],[1,3],[1,2]], for third: [[5],[4],[3],[2],[1]].
It doesn't have to be returned in order, I just need all the elements.
As you can see, another approach is the complementary or inverse or don't know how to call it, but the solution is every combinations of X number of free holes given Y number of holes, so, If I have 10 holes, and 5 marbles, there would be 5 free holes, the array returned would be every combination of 5 that can be formed with (1,2,3,4,5,6,7,8,9,10), which are 252 combinations, and what I need is the 252 combinations.
Examples for the 2nd approach:
Given an array=[1,2,3,4], return every combination for sets of 2 and 3.
Sets of 2
[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Sets of 3
[[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
What I need is the logic to do this, I'm trying to do it in PHP, but I just can't figure out how to do it.
The function would receive the array and the set size and would return the array of sets:
function getCombinations($array,$setize){
//magic code which I can't figure out
return array(sets);
}
I hope this is clear enough and someone can help me, I've been stuck for several days now, but it seems to be just too much for me to handle by myself.
This post, PHP algorithm to generate all combinations of a specific size from a single set, is for all possible combinations, repeating the elements and order doesn't matter, its a good lead, I did read it, but it doesn't solve my problem, it's very different. I need them without repeating the elements and ordered as explained.
Let's say if I have already a set of [3,4] in my array, I don't want [4,3] as an other set.
Here's a recursive solution in PHP:
function getCombinations($array, $setsize){
if($setsize == 0)
return [[]];
// generate combinations including the first element by generating combinations for
// the remainder of the array with one less element and prepending the first element:
$sets = getCombinations(array_slice($array, 1), $setsize - 1);
foreach ($sets as &$combo) {
array_unshift($combo, $array[0]);
}
// generate combinations not including the first element and add them to the list:
if(count($array) > $setsize)
$sets = array_merge($sets, getCombinations(array_slice($array, 1), $setsize));
return $sets;
}
// test:
print_r(getCombinations([1, 2, 3, 4], 3));
Algorithm works like this:
If setsize is 0 then you return a single, empty combination
Otherwise, generate all combinations that include the first element, by recursively generating all combinations off the array excluding the first element with setsize - 1 elements, and then prepending the first element to each of them.
Then, if the array size is greater than setsize (meaning including the first element is not compulsory), generate all the combinations for the rest of the list and add them to the ones we generated in the second step.
So basically at each step you need to consider whether an element will be included or excluded in the combination, and merge together the set of combinations representing both choices.

Random integer with conditions

I have a PHP script where I have an array of integers, let's say $forbidden.
I want to get a random integer from 1 to 400 that is not in $forbidden.
Of course, I don't want any loop which breaks when rand gives a working result. I'd like something more effective.
How do you do this ?
Place all forbidden numbers in an array, and use array_diff from range(1,400). You'll get an array of allowed numbers, pick a random one with array_rand().
<?php
$forbidden = array(2, 3, 6, 8);
$complete = range(1,10);
$allowed = array_diff($complete, $forbidden);
echo $allowed[array_rand($allowed)];
This way you're removing the excluded numbers from the selection set, and nullifying the need for a loop :)
Produce an array of the allowed numbers. Find out the number in this array. Select one of those randomly.

How to sort each numerical value in a number?

I am making a PHP login/register form and to confirm whether someone is actually human and not a bot I am generating a random value that has to be written in a certain way.
For example:
Please write the following number in an increasing manner: 34745
The user should write 34457 and only then will the confirmation work.
The thing is I know how to use the rand() function, that's how I generate the number. But the problem is I do not know how to make PHP sort the generated number's numerical values (for ex.: 64348 -> 34468).
How do I do this? I hope there is a single function for that, as I've seen numerous ways to sort arrays and since they have indexes I only suppose that it should be possible to sort a number's values.
<?php
$number = str_split("647214");
sort($number);
$number = implode($number);
echo $number;
?>
Demo: http://codepad.viper-7.com/RepImd
Instead of using an integer to hold the complete number you could create an array of size n (n is the number of digits). Iterate over the array and use rand() to create random numbers from 0-9 in each position of the array. Now you have an array which can be sorted by using standard sort functions.
I don't think it has single function, but you can make this.
$num = 34745;
$chars = preg_split('/ /', $num, -1, PREG_SPLIT_OFFSET_CAPTURE);
sort($chars);
$res = implode("", $chars);
echo $res;
I didn't tested this, but I hope it works!

PHP dynamic creation of alphabet

I would like to create some arrys. First of all I would like to tell you what it is about so that you understand why I am doing this:
Cryptography.
I want create an array with the alphabet.
such as
$a1 = array("a"=>"b", "b"=>"c",....,"z"=>a");
Alright, that is just a bit of typing so now I want to do it a bit more often. In this case it is x+1=y or in other words for the decoding x=y-1
So lets say I would like to do that with a position change from 1 to 26 - I would have 26 arrays than.
The encryption and decryption itself is not that problem in php and not what I am asking for as it is simple string replacement. But I was wondering if there is anything like this possible to create in an dynamic way by telling:
createAlphabets(1,12)
and it creates me a multidimensional array with 12 alphabet keys?
This is the second part of my question:
is there mathematically figure of more possibilities to swap characters by calculation?
I mean, x+5-3=y is the same like x+2=y so however I calculate it is covered by my 26 arrays? so even if I say: x-5+3=y =? x-2=y it is the same like x+24=y ? isnt it? Please dont bother telling me it might be +25 or +23 and that I am not going to have 24 arrays - its 8am and I didnt sleep - I am just asking about the principle - I dont want you to do my work - I am just looking for some comfirmation and an idea.
$chars = range('a', 'z');
$shift = 5;
$shifted = array_merge(array_slice($chars, $shift), array_slice($chars, 0, $shift));
$alphabet = array_combine($chars, $shifted);
Since there are 26 characters in your alphabet you can only shift them by 26 characters, meaning there are 26 possible combinations.

Categories