I am trying to generate 6 numbers in an array, I'm using the mt_rand function, however I can't have the same number in the array. How would I go about checking for this and generating the number again?
I've thought about making a duplicate array and looping throw and counting how many are in the array, if its more then 1 then re generating the numbers and checking again, however this just seems like a lot of work for something that php might have a native function for that I can't find...
The duplicate thing isn't what I need help with, that is checking the key to the value, I need all values to be unique.
$number_of_numbers = 6;//number_of_numbers in array
$min = 1;//minimum value of number that you want
$max = 15;//maximum value of number that you want
$array = array();
for ($a = 0; $a < $number_of_numbers; $a++) {
$check = 0;//for entering while loop
while ($check !== false) { //pick a number and check if it is in array if it is in the array, pick again and check again
$try[$a] = mt_rand($min, $max); //pick a number
$check = array_search($try[$a], $array);// search that number if it is in the array
}
$array[] = $try[$a]; //add number to array
}
var_dump($array); // show me the array
Is that what you mean? I may get misunderstood about the array keys. Can you explain it a little more?
here is the output. sorry i forgot to add it first.
array(6) { [0]=> int(10) [1]=> int(12) [2]=> int(3) [3]=> int(5) [4]=> int(9) [5]=> int(15) }
Related
Using this function,prt_pattern("341","0"), to print out
0
00
00
000
I'm stuck at converting "341" into integer and store it each number the following was the result i wanted
array[0] = 3
array[1] = 4
array[2] = 1
The flow I'm going to plan for this function is, convert string into int and store it by character, and then find the highest value. After that using 2 for loop, 1st for loop is loop from largest number to 1 and 2nd loop is for looping the number if 4 = 4, print 0 else print " " and value at array[1] -= 1.
Hope anyone can help me with this.
This should work. First I create an array of each number inside the string (cast to integer), then find the highest number from it using the max function.
<?php
$array = (function ($str): array {
$a = [];
$strlen = strlen($str);
for($i = 0; $i < $strlen; $i++) {
$a[] = (int) $str[$i];
}
return $a;
})("3429");
var_dump($array);
/**
array(4) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(2)
[3]=>
int(9)
}
**/
var_dump(max($array)); //int(9)
Test it online here : http://sandbox.onlinephpfunctions.com/code/2e3446d4475c3d69215857ed33a2c1f94f628e0b
edit
As Barmar pointed out in the comments, its way easier to use PHPs function str_split like so:
$array = str_split("3429");
Which will create an array just like previous mentioned.
(I feel silly for not thinking of that function.)
I have an array like this (PHP Code):
$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo","Peter"=>"35", 3=>"Ben" , "Ben"=>"37", 4=>"Nik" , "Joe"=>"43");
I want just get values specific range of index and replace previous arrays values with these new values.Something like this:
$rang= 0-4 OR 0,1,2,3,4 //range of index values.
$my_arr= filtered array value in range index of $range.
I want get this result:
$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo", 3=>"Ben" , 4=>"Nik");
How should I do this?
Update:
I just want to separate the values of the array($my_arr) that are within the range of the specified number of indexes and everywhere in the array and replace all previous array($my_arr) values with these new values.
**
If there were not some of the indexes, Other indexes outside of the specified range for index numbers should not be replaced and only return values of indexes between 0 and 4($my_arr[0]....$my_arr[4]) , and if they don't have value leave empty or do not return something else
array_slice
Extract a slice of the array
array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
Since your array contains mixed keys, you should first sort it so the numeric keys would appear first.
According to your code:
ksort($my_arr, SORT_NATURAL);
$my_sliced_arr = array_slice($my_arr, 0, 4);
Output:
//var_dump($my_sliced_arr)
array(4) {
[0]=>
string(3) "Joe"
[1]=>
string(4) "Mike"
[2]=>
string(4) "Simo"
[3]=>
string(3) "Ben"
}
Manual array_slice
Manual ksort
I found a simple solution after several tests:
foreach($my_arr as $indx=>$val )
{
if(is_int($indx) && ($indx>=0 && $indx<=4))
{
$my_arr[$indx]= $val;
}
else
{ continue; }
}
Try this code
$my_arr=array(0=>"Joe",1=>"Mike",2=>"Simo","Peter"=>"35", 3=>"Ben" , "Ben"=>"37", 4=>"Nik" , "Joe"=>"43");
$numerickeys = array_filter(array_keys($my_arr), 'is_int');
foreach($numerickeys as $num)
{
$ar2[$num] = $my_arr[$num];
}
print_r($ar2);
I am having an issue with understanding why my array containing 3 elements must be sliced into 2 parts each. I wish to access a number I'm pushing into the array only however it seems to print out the index rather than the 'key' value I pushed into it ($number).
I have a 2d array I'm pushing an ID and an integer into, and then sort it :
$array = [[]];
array_push($array, $doc[_id], $number);
array_multisort($array);
I then filter any empty elements:
$array = array_filter($array); //remove null elements
This all works as id expect however the array looks like this by this point:
unrated.array(5)
{
[2]=> object(MongoId)#32 (1)
{ ["$id"]=> string(24) "57b99696ce2350100b000029" }
[3]=> object(MongoId)#31 (1)
{ ["$id"]=> string(24) "57b998ccce2350181700002b" }
[4]=> object(MongoId)#33 (1)
{ ["$id"]=> string(24) "57b99a84ce2350100b00002b" }
[5]=> int(2) [6]=> int(3)
}
Again, this is fine however it means when I loop over the array using the code below it appears to be longer than 3 elements, as I have to slice from 0-6 instead of 0-3:
$array = array_slice($array, 0, 6, true); //only get 3 elements from array
foreach ($array as $key => $value) {
echo $key; //prints out values from 1-5 weirdly.... should just print the $number value
$id = $value->{'$id'};
}
What I am trying to achieve is to find the element in the array with the lowest possible value that was pushed earlier (array_push($array, $doc[_id], $number);) however because I cannot understand why the array is split into 6 rather than 3 parts its even more confusing.
Question in short : How do I access the $number pushed into the array and why is my array 6 seemingly 6 in size when it contains only 3 elements.
Any help would be appreciated, thanks.
To be clear, array_push simply pushes one or more values onto the end of an array. The first argument of array_push is the array you wish to push the value(s) to, and any subsequent argument is a list of values you wish to push. So what you're doing with array_push($array, $doc[_id], $number) is pushing two values ($doc[_id] and $number) to the end of the array $array. array_push will just use the next available index as the key when it adds those values to the array. It will not allow you to specify a key. This is the same thing as doing $array[] = $value.
To specify a key you must assign a value directly to the array key like so: $array[$key] = $value.
I have got the two arrays with my code execution like shown below:
$one = array("IN","US","IN","JP");
$two = array("10","20","30","40");
In above case the sequence for each value is same. i.e. the fist value for IN = 10. For US = 20
I want to add the values for the same countries. So that for india i will have the total of 40.
I have no idea about solving this.
You can merge the two array and use the values from the first array as the index.
$one = array("IN","US","IN","JP");
$two = array("10","20","30","40");
$merge = array();
// Loop through the first array
foreach($one as $index => $value){
// If the country has not been set before, create the index
if(!isset($merge[$value]))
$merge[$value] = $two[$index];
else // Add the value if it's not the first time we 'see' this country
$merge[$value] += $two[$index];
}
Now if you do $merge['IN'], it would give you 40.
Result of var_dump:
array(3) {
["IN"]=> int(40)
["US"]=> string(2) "20"
["JP"]=> string(2) "40"
}
If I want to remove the last element of an array, I can use either of these two code:
array_pop($array); (the return value is not used)
unset($array[count($array) -1]);
Is there any performance or semantic difference between them?
If not, which is preferred?
unset is no good if you need to "do" anything with the removed value (unless you have previously assigned it to something elsewhere) as it does not return anything, whereas array_pop will give you the thing that was the last item.
The unset option you have provided may be marginally less performant since you are counting the length of the array and performing some math on it, but I expect the difference, if any, is negligible.
As others have said, the above is true if your array is numerical and contiguous, however if you array is not structured like this, stuff gets complicated
For example:
<?php
$pop = $unset = array(
1 => "a",
3 => "b",
0 => "c"
);
array_pop($pop);
// array looks like this:
// 1 => "a", 3 => "b"
$count = count($unset) - 1;
unset($count);
// array looks like this because there is no item with index "2"
// 1 => "a", 3 => "b", 0 => "c"
array_pop($array) removes the last element of $array.
unset($array[count($array) -1]); removes the element at index count($array) -1. This element is not neccesarily the last element of the array.
Consider $array = array(0 => 'foo', 2 => 'bar', 1 => 'baz'). In this case , $array[1] is the last element. The code
foreach (array(0 => "foo", 2 => "bar", 1 => "baz") as $key => $value)
echo "$key => $value\n";
prints
0 => foo
2 => bar
1 => baz
Moreover, an element at index count($array) -1 might not even exist. There can be gaps in the set of indices and integer indices can be mixed with string indices.
The return values are different. array_pop returns the last element, while unset doesn't return anything.
For simply removing the last element, array_pop would be better because you don't need to execute count($array)-1, and it is cleaner and more readable.
Yes there is.
Firstly, the unset() option will only work for numerical, contiguous arrays. If your array contains elements that are not numerical, or has any gaps in its numerical sequence, then the unset() call will get the incorrect value from count() and will fail.
Secondly, assuming your array is numerical and contiguous, there is still a difference:
array_pop() will also give you back the value of the popped element as a return value. unset() will not do this.
So if you need to keep using the data, use array_pop().
If you don't need to keep the value, then no, it probably doesn't matter too much which one you use, I suspect that array_pop() may be faster (due to not needing to call count()), but I haven't checked, and to be honest, unless you're doing thousands of calls, the difference will be negligible anyway.
Except for the obvious differences in call syntax and return value...
array_pop always pops whatever is last.
Your count - 1 unsets an element by its numeric id, which only works as you expect it to if all elements are continuously numerically indexed.
For what it's worth, using a bit of existing code that gets called a bit over 2000 times in a run, I put in a $whatevers[]=$whatever (a parameter value) at the top and and array_pop($whatevers) at the bottom.
The function calls itself recursively down to about 7 or 8 levels and (of course) I made $whatevers static so the array grew and shrunk.
The result? The difference between this code in and commented out was unmeasurable down to 100ths of a second on a windows 7 laptop. It varied a fair bit because of other things, but over lots of runs the difference in the averages was meaningless.
The performance overhead of array_pop() just isn't worth a second thought and though unset might be theoretically faster, nobody will ever be able to detect the difference.
As others have mentioned - their functionality is the same, bar the return value from array_pop. However, it's also worth mentioning the possible performance issue of the unset method on a large array due to the count() call.
As Oswald mentions, it is also worth noting that unset() will only be working as expected on numeric keys.
Yes there is a difference
array_pop() will also return removed element eg: last element, and
unset() will not return any thing
I would prefer unset() but you call count() which can consume performance.
An alternative choice is array_slice(array, offset, length, preserve_keys) :
$array = array_slice($array, 0, -1, true);
Another consideration to take into account is that if after deleting the last item you push a new element, you get different results in which the index the new element is placed at:
unset
php > $a = [1,2,3];
php > var_dump($a);
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
php > unset($a[2]);
php > var_dump($a);
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
php > $a[] = 5;
php > var_dump($a);
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[3]=>
int(5)
}
As you see, the new element is placed at index 3 instead of 2.
array_pop
php > $a = [1,2,3];
php > var_dump($a);
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
php > array_pop($a);
php > var_dump($a);
array(2) {
[0]=>
int(1)
[1]=>
int(2)
}
php > $a[] = 5;
php > var_dump($a);
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(5)
}
Now the new element is placed at index 2. Maybe this is the most desirable behaviour.