PHP return randomised array - php

I am trying to create a new array from an existing one with a random number of records between 2 and 10, I have this so far
//Select a random number
$random_number = (rand(2,10));
// Setup an array of names
$names = array("john", "joe", "simon", "peter", "paul");
// Create new array
$random_field_names = array_rand($names, $random_number);
print_r($random_field_names);
This gives me an array that looks like this
Array
(
[0] => 0
[1] => 10
[2] => 11
)
Where am I going wrong?

Use the key to get the value you want :
//Select a random number
$random_number = (rand(2,10));
// Setup an array of names
$names = array("john", "joe", "simon", "peter", "paul");
// Create new array
$random_field_names = array_rand($names, $random_number);
print_r($names[$random_field_names]);

The description of array_rand explains why you don't get the names (I stress in bold):
Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.
You seem to want the values. That you can achieve like this:
array_intersect_key($names, array_flip(array_rand($names, $random_number)));
Also make sure your random number is not greater than the array size:
$random_number = rand(2,5);
$names = array("john", "joe", "simon", "peter", "paul");
$result = array_intersect_key($names, array_flip(array_rand($names, $random_number)));
print_r ($result);
Note that the result maintains the original keys. If you want to renumber the keys to get an indexed array starting with index 0, then apply array_values to the result:
$result = array_values(array_intersect_key($names, array_flip(array_rand($names, $random_number))));

syntax error on line 5 - missing quote after "simon
array_rand() returns random key(s), not values
rand(2,10) won't work in all cases as there are only 5 entries in the array; from PHP docs: Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned.
If you want to randomize the entire array, use shuffle().

Related

Counting unique occurences of country in a php array and adding them to a statistics array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Unique entries in an array
Let assume the array is sorted, how can I get number of counts for each unique items
Example:
$array = array ("bye", "bye", "bye", "hello", "hello");
Output:
bye = 3
hello = 2
If you want to get the total count of unique values in a specified column within a given array, as a simple integer (rather than another array) try something simple like this:
$uniqueCount = count(array_unique(array_column($data, 'column_name')));
// (where $data is your original array, and column_name is the column you want to cycle through to find the total unique values in whole array.)
var_dump(array_count_values(array("bye", "bye", "bye", "hello", "hello")));
You can use array_count_values.
print_r(array_count_values($array));
will return :
Array
(
[bye] => 3
[hello] => 2
)
You can use array_count_values on your array which would return something like:
array(2){
["bye"]=> int(3)
["hello"]=> int(2)
}
Example Usage:
$unique = array_count_values($my_array);

how do you count the number of words present in the array below? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Unique entries in an array
Let assume the array is sorted, how can I get number of counts for each unique items
Example:
$array = array ("bye", "bye", "bye", "hello", "hello");
Output:
bye = 3
hello = 2
If you want to get the total count of unique values in a specified column within a given array, as a simple integer (rather than another array) try something simple like this:
$uniqueCount = count(array_unique(array_column($data, 'column_name')));
// (where $data is your original array, and column_name is the column you want to cycle through to find the total unique values in whole array.)
var_dump(array_count_values(array("bye", "bye", "bye", "hello", "hello")));
You can use array_count_values.
print_r(array_count_values($array));
will return :
Array
(
[bye] => 3
[hello] => 2
)
You can use array_count_values on your array which would return something like:
array(2){
["bye"]=> int(3)
["hello"]=> int(2)
}
Example Usage:
$unique = array_count_values($my_array);

How to get the first unique number in array using PHP?

Consider an array [1,2,1,2,3,4,5,]. I need to make a function in PHP that will return the first unique number in that array, in this case, 3.
Or
How we can remove all repeated elements of the array. In this case returns [3,4,5].
You can use following snippet,
$yourArr = [1,2,1,2,3,4,5];
// count the number of occurences of each value
$res = array_count_values($yourArr);
// filtering only unique values
$res = array_filter($res, function($item){ return $item == 1; });
print_r();
// to fetched first unique
// fetching filtered values as keys
$un = array_keys($res);
echo $un[0]; // will output 3
array_count_values — Counts all the values of an array
array_filter — Filters elements of an array using a callback function
array_keys — Return all the keys or a subset of the keys of an array
Working Demo
Output:-
Array
(
[0] => 3
[1] => 4
[2] => 5
)

get ordinal value for letter PHP

I've been given a datafile where the original creator used alphabetical rather than numeric values to show order.
For example, if there's ten items, they'd be named:
12342313A
12342313B
12342313C
12342313D
12342313E
...
I need to import these values into a mySQL table that has order as a required int column, and I need to convert the letter to a number.
Is there a function in PHP to get a numeric value for a letter? Or will I need to do a substr to grab the trailing letter, and create an indexed array of letters and just do a lookup against that array?
I'm hesitant to do the simple way above, since I don't know how many objects could potentially exist, and I could need to write an array from A-AAAA or something.
Try converting it from base 36 to base 10 using base_convert(), I.e. base_convert($str, 36, 10). You might need to strtolower it first, and it'll only work if its not case sensitive.
PHP has a simple way to create that array, so you could write a function to figure all that out for you and do something like:
function str_to_num($letters, $max = 'ZZZZZZ') {
$count = 0;
for ($i = 'A'; $i < $max; $i++) {
$count++;
if ($letters == $i)
return $count;
}
}
Then you could do the substr, find the letters at the end, and then pass it into the function:
str_to_num('A'); // returns 1
str_to_num('AB'); // returns 28
str_to_num('AC'); // returns 29
str_to_num('ABC'); // returns 731
Something like that, anyway.
Good luck.
Assuming this is a one-time problem that you've got to correct and won't encounter moving forward, I suggest you use sort to... erm, sort out the problem. Let's say you have all those alpha-numeric order fields in an array, like so:
$vals = array (
'12342313A',
'12342313D',
'12342313E',
'12342313B',
'12342313C'
);
Those are all mixed up, not in order. But, you can call the function sort (docs) on that array and PHP does a decent job of making sense out of it:
print '<pre>Unsorted: ';
print_r($vals);
print '</pre>';
sort($vals);
print '<pre>Sorted: ';
print_r($vals);
print '</pre>';
/*
Unsorted: Array
(
[0] => 12342313A
[1] => 12342313D
[2] => 12342313E
[3] => 12342313B
[4] => 12342313C
)
Sorted: Array
(
[0] => 12342313A
[1] => 12342313B
[2] => 12342313C
[3] => 12342313D
[4] => 12342313E
)
*/
So far, so good. Now, you've got them ordered, and as a bonus you can use the index of the array as your new field in the database. Alter the table and add a field to hold the new value; we'll call this field numeric_order, and in my sample I've called the field that currently holds the alpha-numeric sort data string_order. Loop your sorted array and update the database (for example):
foreach ($vals as $x=>$v) {
$sql = 'UPDATE myTable SET numeric_order = '.($x+1).' WHERE string_order = "'.$v.'"';
}
I add 1 to x in the loop based on the assumption that you don't want anything to have 0 for the order - if that isn't a concern, then you can just use x. This is also predicated on the assumption that no two rows have the same alpha-numeric sort value.
If they do, then all is not lost! Start with your array looking like this:
$vals = array (
3=>'12342313A',
15=>'12342313D',
66=>'12342313E',
101=>'12342313B',
200=>'12342313C'
);
... the numeric keys would represent the unique/primary key of the corresponding row. Instead of sort, which does not preserve keys, use asort (which does preserve keys - docs), and then your loop looks like this:
$ord = 1
foreach ($vals as $x=>$v) {
$sql = 'UPDATE myTable SET numeric_order = '.$ord.' WHERE id = "'.$x.'"';
$ord++;
}
If my base assumption is wrong, and you'll continue to deal with this method of ordering rows, then in my humble view you ought to re-consider your data design.
use ord() with substr and subtract 64. This will set A to 1, B to 2, etc...
From what you have above, it seems like your values (last digit, at least) can be thought as being hex numbers. You can then transform them into decimal numbers through the hexdec function.
http://php.net/manual/en/function.hexdec.php

Looking up keys for a multi-dimensional array

I have an array with a key and 3 values (day, start_time, end_time). I want to keep adding certain entries into this array while making sure each entry is unique. That means that every time I try to add an item into the array, I want to make sure it does not already exist in it. If it does exist, I want to be able to find the key that indicates that entry.
For example, this is the pre-existing array:
$array [0][0] = Monday
$array [0][1] = 2
$array [0][2] = 4
$array [1][0] = Tuesday
$array [1][1] = 3
$array [1][2] = 5
If I try to insert (Wednesday, 3, 5), then it should make the entry in the index 2.
If I try to insert (Monday, 2, 4), I need to be able to know that it is already in there and is indexed by 0.
How do I go about doing this?
I agree with the other answers here — it might be better to restructure your array so that there is no need to worry about duplication at all.
If you want to keep your current structure, however: use array_search.
$array = ...
$unique_check = array_search(array('Monday', 2, 4), $array);
if ( $unique_check === false )
// add to array
else
// $unique_check = the array key at which the existing matching element is located
Why not organize the array this way?
$array [Monday][0] = 2
$array [Monday][1] = 4
$array [Tuesday][0] = 3
$array [Tuesday][1] = 5

Categories