hi all i need a snippet i know can do it with a bit of coding
but i need a snippet
i want an array of say choosable length like getArray(50) gives me a array of size 50
like we declare na ?
array[50] in other languages
and i want to fill it with some random data.
I want some real cool methods!
Like this
array(
0=>"sds"
1=>"bds"
....
n=>"mds"
);
You can get an array of a specific length, that is pre-filled with a given value, using the array_fill() function. I don't think that there is an in-built function that will generate arrays with random contents, though.
$myArray = array_fill(0, 50, null);
What form exactly do you want the array elements to take? You want them to be a lowercase letter frollowed by "ds"?
$myArraySize = 50;
$myArray = array_fill(0, $myArraySize, '_ds');
for ($i=0; $i<$myArraySize; $i++) {
$myArray[$i][0] = chr(mt_rand(97, 122));
}
this can be used to get array's of specific length filled with 24 character long string. Use it according to your use.
<?php
function generate_array($num)
{
$input = array();
$result = array_pad($input, $num, 0);
foreach($result as $key=>$val)
{
$result[$key] = gen_rand_str_24();
}
return $result;
}
function gen_rand_str_24()
{
return pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand());
}
$result = generate_array(5);
print_r($result);
?>
Just do:
$arr = array();
$arr[] = "a";
$arr[] = "b";
Or similar:
$arr = array( 0 => "a",
1 => "b");
You don't need to set a length before filling it in PHP.
Related
I have this code:
public function get_names($number){
$names = array(
'None',
'Anton',
'bertha',
'Cesa',
'Dori',
'Egon',
'Frank',
'Gollum',
'Hans',
'Kane',
'Linus',
'Moose',
'Nandor',
'Oliver',
'Paul',
'Reese');
$bin = strrev(decbin($number));
$len = strlen($bin);
$output = array();
foreach(str_split($bin) as $key=>$char)
{
if ($key == sizeof($names)){
break;
}
if($char == 1)
{
array_push($output,$names[$key]);
}
}
return $output;
}
When I now call the function with number - let's say - 32256 I would get an array with "Kane, Linus, Moose, Nandor, Oliver, Paul".
Can anyone tell me what I would have to do when I want to give a certain names array and wanna get the number as a result where the certain bits are included? So exactly the other way around.
I found that code somewhere which works fine. But I need it vice versa.
Thanks in advance!
Andreas
EDIT: I want to know the decimal number when I e.g. have an array with "Anton, bertha,Cesa". I want to store those in a database instead of storing arrays with names each time. And when I need the names I just take the decimal number from database and use my function to get my name arrays.
If you just take the position in your $names array as being the bit position, you raise 2 to this position to give it the correct bit position and keep a running total of the items found...
$input = ["Cesa", "Gollum", "Hans"];
$output = 0;
foreach ( $input as $digit ) {
$output += pow(2,array_search($digit, $names ));
}
echo $output; // 392
with
$input = ["Kane", "Linus", "Moose", "Nandor", "Oliver", "Paul"];
gives
32256
Or as Barmar points out in his comment, you can save the lookup by inverting the names array using array_flip() which will mean that looking up each key will give the position in the array...
$output = 0;
$names = array_flip($names);
foreach ( $input as $digit ) {
$output += pow(2,$names[$digit]);
}
echo $output;
I store a number in a string. My code shuffles the digits into different permutations.
Example if the input is:
'123'
then the output permutations will be:
123,132,213,231,321,312
If the input string has repeated digits, my code does not work, and goes into an infinite loop.
Example inputs that don't work:
11,22,33,44,55,455,998,855,111,555,888,222 etc.
My code:
<?php
function factorial($n){
if($n==1) return $n;
return $n*factorial($n-1);
}
$a = '1234';
$_a = str_split($a);
$num = count($_a);
$ele_amnt = factorial($num);
$output = array();
while(count($output) < $ele_amnt){
shuffle($_a);
$justnumber = implode('', $_a);
if(!in_array($justnumber , $output))
$output[] = $justnumber;
}
sort($output);
print_r($output);
Can anyone explain why and how to fix it?
Short version: Your terminating condition for the while loop "is" permutational while your if(!in_array...) test "is" combinational.
Let's assume $a=11;: then $ele_amnt is 2 and your while loop will stop when the array $output contains more than one element.
Your shuffle/implode code can produce either the string <firstelement><seconelement> or <secondelement><firstelement>, both being 11.
And if(!in_array( $justnumber , $output)) allows only one of them to be appended to $output. So count($output) will be 1 after the first iteration and will stay 1 in perpetuity. Same for every $a with duplicate digits.
shuffle() changes the position of elements in an array at random. SO, the performance of the algorithm depends on ....luck ;-)
You might be interested in something like https://pear.php.net/package/Math_Combinatorics instead.
Your output array will contain less permutations if you have repeated characters in your input. So your loop never completes.
You could map your inputs, then later map back from your output, and then filter to do as you desire:
// For a string '122' we get the permutations of '123' first and then process.
$output = op_code_no_repeats('123');
$filtered = array();
foreach($output as $permutation) {
$filtered[] = str_replace('3', '2', $permutation);
}
$filtered = array_unique($filtered);
var_dump($filtered);
Outputs:
array (size=3)
0 => string '122' (length=3)
2 => string '212' (length=3)
3 => string '221' (length=3)
Your code with guards on the factorial and permutation functions:
function factorial($n)
{
if(! is_int($n) || $n < 1)
throw new Exception('Input must be a positive integer.');
if($n==1)
return $n;
return $n * factorial($n-1);
};
function op_code_no_repeats($a) {
$_a = str_split($a);
if(array_unique($_a) !== $_a)
throw new Exception('Does not work for strings with repeated characters.');
$num = count($_a);
$perms_count = factorial($num);
$output = array();
while(count($output) < $perms_count){
shuffle($_a);
$justnumber = implode('', $_a);
if(!in_array($justnumber , $output))
$output[] = $justnumber;
}
sort($output);
return $output;
}
I am looking for elegant way to sort two of three values stored in one array. The third one can be ignored but i dont want to loose it (so unseting is not an option).
Imagine such array:
$r = Array("tree_type" => 1, "tree_height" = 5, "tree_age" = 2);
If tree_height is bigger then it's age i want to swap tree height with tree_age, so tree height is always smaller number then age.
Now I am sorting it like this:
if ( $r['tree_height'] > $r['tree_age'] ) {
$tmp = $r['tree_height'];
$r['tree_height'] = $r['tree_age'];
$r['tree_age'] = $tmp;
}
It works perfectly fine, but i am looking for more elegant way. The best solution would be sth like this:
fname($r, $r['tree_height'], $r['tree_age']);
fname would always swap second argument with third if it's bigger then third, otherwise would do nothing.
Any advice would be appreciated.
Kalreg.
ANSWER:
The shortest answer, without condition is:
$tmp = Array($r['tree_height'], $r['tree_age'])
sort($tmp);
You could just encase the code into a function:
function swap(&$arr){ //NOTE SIGN & meaning passing by reference.
if ($arr['tree_height'] > $arr['tree_age']){
$cache_age = $arr['tree_age'] ;
$arr['tree_age'] = $arr['tree_height'] ;
$arr['tree_height'] = $cache_age ;
}
}
$r = array("tree_type" => 1, "tree_height" => 5, "tree_age" => 2);
swap($r);
var_dump($r);
Another elegant solution: (based on Is there a PHP function for swapping the values of two variables?)
function swap(&$arr){ //NOTE SIGN & meaning passing by reference.
if ($arr['tree_height'] > $arr['tree_age']){
list($arr['tree_height'], $arr['tree_age']) = array($arr['tree_age'], $arr['tree_height']);
}
}
This might work (not tested):
function fname(&$a, &$b) {
if ($a <= $b)
return;
$t = $a;
$a = $b;
$b = $t;
}
fname($r['tree_height'], $r['tree_age']);
EDIT: Maybe You wanted something like this?
function fname(&$array, $name1, $name2) {
if ($array[$name1] <= $array[$name2])
return;
$t = $array[$name1];
$array[$name1] = $array[$name2];
$array[$name2] = $t;
}
fname($r, 'tree_height', 'tree_age');
I have a string that will be exploded to get an array, and as we know, the output array key will start from 0 as the key to the first element, 1 for the 2nd and so on.
Now how to force that array to start from 1 and not 0?
It's very simple for a typed array as we can write it like this:
array('1'=>'value', 'another value', 'and another one');
BUT for an array that is created on the fly using explode, how to do it?
Thanks.
$exploded = explode('.', 'a.string.to.explode');
$exploded = array_combine(range(1, count($exploded)), $exploded);
var_dump($exploded);
Done!
Just use a separator to create a dummy element in the head of the array and get rid of it afterwards. It should be the most efficient way to do the job:
function explode_from_1($separator, $string) {
$x = explode($separator, $separator.$string);
unset($x[0]);
return $x;
}
a more generic approach:
function explode_from_x($separator, $string, $offset=1) {
$x = explode($separator, str_repeat($separator, $offset).$string);
return array_slice($x,$offset,null,true);
}
$somearray = explode(",",$somestring);
foreach($somearray as $key=>$value)
{
$otherarray[$key+1] = $value;
}
well its dirty but isn't that what php is for...
Nate almost had it, but needed a temporary variable:
$someArray = explode(",",$myString);
$tempArray = array();
foreach($someArray as $key=>$value) {
$tempArray[$key+1] = $value;
}
$someArray = $tempArray;
codepad example
$array = array('a', 'b', 'c', 'd');
$flip = array_flip($array);
foreach($flip as &$element) {
$element++;
}
$normal = array_flip($flip);
print_r($normal);
Try this, a rather funky solution :P
EDIT: Use this instead.
$array = array('a', 'b', 'b', 'd');
$new_array = array();
$keys = array_keys($array);
for($i=0; $i<count($array); $i++) {
$new_array[$i+1] = $array[$i];
}
print_r($new_array);
I agree with #ghoti that this task is probably an XY Problem. I can't imagine a valid/professional reason to start keys from 1 -- I've never needed this functionality in over 10 years of development. I'll offer a compact looping approach, but I'll probably never need it myself.
After instatiating a counter which is one less than the desired first key, you can use a body-less foreach() as a one-liner.
Code: (Demo)
$i = 0;
$result = [];
foreach (explode('.', 'a.string.to.explode') as $result[++$i]);
var_export($result);
I have a string with a lot of different numbers. I am trying to create a new random number and add it to the string.
The part I need help with is "if the number already exists in the string, create a new random number, and keep doing it until a number is created that does not yet exist in the string".
// $string contains all the numbers separated by a comma
$random = rand(5, 15);
$existing = strpos($string, $random);
if ($existing !== false) { $random = rand(5, 15); }
$new_string = $string.",".$random;
I know this isn't quite right as it will only check if it's existing once. I need it to keep checking to make sure the random number does not exist in the string. Do I use a while loop? How would I change this to work properly?
Your help is much appreciated.
A solution that works like Endijs ... but I want to post that :)
$string = '6,7,8';
$arr = explode(',', $string);
$loop = true;
while($loop) {
$randomize = rand(5, 15);
#var_dump($randomize);
$loop = in_array($randomize, $arr);
if (!$loop) {
$arr[] = $randomize;
}
}
$newString = implode(',', $arr);
var_dump($newString);
Checking data in string is not the best solution. Thats because if your random number will be '5', and in string you will have 15, strpos will find accurance of 5. I would convert string to array and do search on it.
$a = explode(',' $your_string);
$random = rand(5, 15);
while (in_array($random, $a))
{
$random = rand(5, 15);
}
$a[] = $random;
$your_string = implode(',', $a);
Update - just be careful - if all possible variables will be already in string, it will be endless loop.