Randomly picking out of an array in PHP - php

I have an array that has values like 1, 5, 6, 9, 11, 45, 56, etc. What I'm trying to do is to randomly one value, perhaps 6. Then I want to pick a random value excluding 6 (so no doubles). Then a random value excluding the last two, all from inside an array. Any help? I'm trying to do this without while loops but if they are necessary then so be it.

I suggest the following:
# pick a random key in your array
$rand_key = array_rand($your_array);
# extract the corresponding value
$rand_value = $your_array[$rand_key];
# remove the key-value pair from the array
unset($your_array[$rand_key]);
See: array_rand, unset.

Shuffle the array first and then use it as a stack:
$a = array(1, 5, 6, 9, 11, 45, 56);
shuffle($a);
// now you can have your picks:
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
$pick = array_pop($a);
...

I would probably shuffle the array and get the first/last x value

Related

Append each item of arrays to a new array [duplicate]

This question already has an answer here:
Multi dimensional loops from 4 existing arrays [duplicate]
(1 answer)
Closed 4 months ago.
I have 4 different arrays with the same count of elements. I want to add each element of each array into a new array. For example: $id_array[0] should be added into $artikel_combined. Then $name_array[0] into $artikel_combined. And so on. Then when all 4 arrays are done with index 0, then they should start with index 1 and so on.
I tried with this code but it just combines all the arrays, but not what i want.
// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);
// This is the point where i fail, because it just combines and I'm out of ideas
$arr = array_merge($id_array, $name_array, $x_array, $y_array);
$artikel_combined = [];
// Removing new Lines from the elements
foreach ($arr as $item) {
$artikel_combined[] = trim($item);
}
if the array have always the same count of elements you can cycle through them and add them together.
like
$count = count($id_array);
$artikel_combined = [];
for($i=0;$i<$count;$i++){
$artikel_combined[$i][] = id_array[$i];
$artikel_combined[$i][] = trim(name_array[$i]);
$artikel_combined[$i][] = trim(x_array[$i]);
$artikel_combined[$i][] = trim(y_array[$i]);
}
probably not the best way to solve the problem, but it should do the job :)
Using array_merge: "Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one."
But you want to join up the same array key for every array into a new array, resulting in a multidimensional array.
You could also do so using array_map passing null as the first parameter:
// LoadIni creates an array every nth line.
$id_array = $ini_obj->LoadIni($f_art, 0, 9, 999);
$name_array = $ini_obj->LoadIni($f_art, 1, 9, 999);
$x_array = $ini_obj->LoadIni($f_art, 2, 9, 999);
$y_array = $ini_obj->LoadIni($f_art, 4, 9, 999);
$artikel_combined = array_map(null, $id_array, $name_array, $x_array, $y_array);

Arrange an array of positive integers to form the largest numerical string

Can someone help me for my College Exam. I tried to search but Im totally newbie in php and Im still studying
Here's what i want, Can you give me some Idea or function so that I can arrange an array of positive integers to form the largest numerical string?
For Example:
$arrnew = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
assert(getLargestNumStr($arrnew) == 98765432110, 'Basic test 9-8-7-6-5-4-3-2-1-10');
Hope you can help me.
This is a nice problem, this could be solved by this observation:
let's consider two elements in the array x and y, so assume that for the two numbers created by appending these two elements: xy > yx => in the final result, x will always be in front of y, otherwise, we could easily create a larger number by swapping the position of x and y in the result.
=> We could simply create a custom sort based on this observation, when compare two number x and y.
Give a try with below code if it solve your problem...
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$text='';
foreach($array as $arr){
$text.=$arr;
}
$string = str_split($text, "1");
$new_text = implode(",", $string);
$output=explode(",",$new_text);
rsort($output);
$final = '';
foreach($output as $out){
$final.=$out;
}
echo $final;
Try sorting the array in descending order with something like arsort() and concatinate the Array-elements to a string. This should give you the highest possible number.
Try this
$arrnew = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arsort($arrnew);
$str = str_replace(',','',join(',',$arrnew));
$arr1 = str_split($str);
arsort($arr1);
print_r($arr1);
echo implode('',$arr1);
Demo

comma separated string to array with key php

I have a string
$tailored_information="3, 5, 10, 13, 7, 6";
Now I have need to make an array like
$input_array = array("Id" => 3, "Id" => 5);
I am using this but not work cause i cant add key ID
explode(",", $tailored_information)
As been told, you can't have array with the same key, because it is a hash table, which will override the "id" every time.
I suggest you to use simply
explode(", ", $id_array);
or
explode(", ", $another_arr['id']);
like this you will group the data by id...
If you wish to go into some more complicated - you could create your own data structure, which will be non-unique array - where you will divide different values by key...
this way the print version will be whatever you want...
An array has to have unique keys. Also, you will now have spaces in your values
What you could do is explode by ", " and then take that array as your array straight away. If the key you want/need is always "Id" then it doesn't matter anyway.
<?php
$abc = "3, 5, 10, 13, 7, 6";
$new_array = explode(',',$abc);
$new_id_array = array();
foreach($new_array as $key=>$val){;
$new_id_array[$key]['id'] = $val;
}
print_r($new_id_array);
?>
you can not put same key in a array key. so for that you have to create a nested array.and that will solve ur problem and now you can have same array key, but in different arrays.OR
$abc = "3, 5, 10, 13, 7, 6";
$new_array = explode(',',$abc);
foreach($new_array as $key=>$val){
$new_id_array['id_'.$key] = $val;
}

Using array_slice() to get first few values

I'd like to use an array_slice to get every value in an array iterated over, except for the current one, the one before it, and all the others until the end of the array.
So for example, say I have 5 elements:
[1, 2, 3, 4, 5]
I want a way for a condition to fire on 3, cut it out, and then also cut out 4 and 5. I have this, but I don't think it's correct:
$items = array_slice($items, $itemcount - 1);
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
So if you want to get the 3,4,5 your offset should be 2, because the array key ( starts from 0 ex: 0,1,2,3,4). i didn't use length in this one because i want to get it till the end (5)
$items = array_slice($items, 2);
If you want to grag 1,2 it should be like this. ( i use length 2 because i want to get the first 2 keys)
$items = array_slice($items, 0, 2);
Example

Array sorting/searching technique in PHP

I have an array let say $array = array(2, 1, 8, 3, 6, 0, 10, 10)and I want to get second largest value of that array.
Which sorting/searching technique will be best & how could I use it?
I'd just remove the duplicates from your array (using array_unique) and then use rsort (which uses Quicksort) with the SORT_NUMERIC flag to sort numerically from highest to lowest:
$array = array(2, 1, 8, 3, 6, 0, 10, 10);
$unique_array = array_unique($array);
rsort($unique_array, SORT_NUMERIC);
$second_highest = $unique_array[1]; // will be 8
The PHP manual has a comparison of sorting techniques.
Something like this?
$array = array(2, 1, 8, 3, 6, 0, 10, 10);
rsort($array);
echo $array[1]; // 10
this reverse sorts the array and then outputs the second element.
Edit: if you want the second highest unique value, just add an array_unique call:
$array = array(2, 1, 8, 3, 6, 0, 10, 10);
$array = array_unique($array);
rsort($array);
echo $array[1]; // 8
you could use rsort, but it will do a lot of additional operations which are not needed (quick sort has O(logn) complexity).
It might be a lot faster if you pass the array only in one pass like this (O(n)):
$largest=$array[0];
$secondLargest=null; //none present, by default
foreach($array as $value)
if($value>$largest)
{
$secondLargest=$largest;
$largest=$value;
}
it will be significantly faster on large arrays, but it is only good when you want the first, second, maybe third largest element. In all other cases it would be more reasonable to sort the array and take the N'th largest element dynamically.

Categories