Select 2 random elements from associative array - php

So I have an associative array and I want to return 2 random values from it.
This code only returns 1 array value, which is any of the 4 numbers at random.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$key = array_rand($array); //array_rand($array,2); Putting 2 returns Illegal offset type
$value = $array[$key];
print_r($value); //prints a single random value (ex. 3)
How can I return 2 comma separated values from the array values only? Something like 3,4?

array_rand takes an additional optional parameter which specifies how many random entries you want out of the array.
$input_array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$rand_keys = array_rand($input_array, 2);
echo $input_array[$rand_keys[0]] . ',' . $input_array[$rand_keys[1]];
Check the PHP documentation for array_rand here.

Grab the keys from the array with array_keys(), shuffle the keys with shuffle(), and print out the values corresponding to the first two keys in the shuffled keys array, like so:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_keys( $array);
shuffle( $keys);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];
Demo
Or, you can use array_rand()'s second parameter to grab two keys, like so:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_rand( $array, 2);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];
Demo

There is a more efficient approach that preserves keys and values.
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
Check the documentation here

$a=rand(0,sizeof($array));
$b=$a;
while ($a==$b) $b=rand(0,sizeof($array));
$ar=array_values($array);
$element1=$ar[$a];
$element2=$ar[$b];
Should be more efficient than shuffle() and freinds, if the array is large.

Related

create array of POSTs from string array [duplicate]

I am searching for a built in php function that takes array of keys as input and returns me corresponding values.
for e.g. I have a following array
$arr = array("key1"=>100, "key2"=>200, "key3"=>300, 'key4'=>400);
and I need values for the keys key2 and key4 so I have another array("key2", "key4")
I need a function that takes this array and first array as inputs and provide me values in response. So response will be array(200, 400)
I think you are searching for array_intersect_key. Example:
array_intersect_key(array('a' => 1, 'b' => 3, 'c' => 5),
array_flip(array('a', 'c')));
Would return:
array('a' => 1, 'c' => 5);
You may use array('a' => '', 'c' => '') instead of array_flip(...) if you want to have a little simpler code.
Note the array keys are preserved. You should use array_values afterwards if you need a sequential array.
An alternative answer:
$keys = array("key2", "key4");
return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);
foreach($input_arr as $key) {
$output_arr[] = $mapping[$key];
}
This will result in $output_arr having the values corresponding to a list of keys in $input_arr, based on the key->value mapping in $mapping. If you want, you could wrap it in a function:
function get_values_for_keys($mapping, $keys) {
foreach($keys as $key) {
$output_arr[] = $mapping[$key];
}
return $output_arr;
}
Then you would just call it like so:
$a = array('a' => 1, 'b' => 2, 'c' => 3);
$values = get_values_for_keys($a, array('a', 'c'));
// $values is now array(1, 3)

Independent Nested Loops in PHP

Say i have two different arrays. I want to get each value from the first array, and add to it some values of each key in the second array. How do i do this please?
I tried using a foreach loop inside a foreach loop and for each value in the first array, it appends each value of the second array which isn't what i want
$array1 = array(chris, kate, john, jane);
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
foreach($array1 as $name){
foreach($array2 as $k => $v){
echo $name . "-" . $v;
}
}
I want my output to look like this
chris-1
kate-2
john-3
jane-4
Sometimes, the count of both array aren't the same. Some values in the first array produces an empty string, so in cases like that, it should just skip the value. Once the empty string in array1 is skipped or deleted, the count then matches array2
My above nested loop can't give me this. How do i go about this please?
Firstly I would use array_filter() to remove the empty strings from $array1:
$array1 = array(chris, kate, john, jane);
$array1 = array_filter($array1, function($value) {
return $value !== '';
});
Now we need to reindex the array to account for the gaps we made when removing empty strings.
$array1 = array_values($array1);
Considering you don't use the 'first', 'second', etc keys in $array2 for anything, we can just get rid of them using array_values(). This will leave us with an array like array(1,2,3,4) which will make accessing the data later on a little easier.
$array2 = array('first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4);
$array2 = array_values($array2);
Now we can loop through the first array and access the same position in the second array to create the final string.
// Assign the current element's numeric position to the $i variable on each iteration.
foreach($array1 as $i => $name){
echo $name . "-" . $array2[$i];
}
Final Code
$array1 = ['chris', 'kate', '', 'john', 'jane'];
$array1 = array_filter($array1, function ($value) {
return $value !== '';
});
$array1 = array_values($array1);
$array2 = ['first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4];
$array2 = array_values($array2);
foreach ($array1 as $i => $name) {
echo $name . "-" . $array2[$i];
}

php. array_values function. how to get mapping from old keys to new keys?

There is function array_values in PHP such that
$array2 = array_values($array1);
$array2 has the same values as $array1 but keys are from
0 to sizeof($array1) - 1. Is it possible to get mapping from old keys to new keys?
EDIT. I will explain on an example:
$array1 = array( 'a' => 'val1', 'b' => 'val1');
$array2 = array_values( $array1 );
so now array2 has next values
$array2[0] = 'val1'
$array2[1] = 'val2'
How get array3 such that:
$array3['a'] = 0
$array3['b'] = 1
To produce a key map you need to first get the keys into a regular array and then flip the keys and values:
$array1_keymap = array_flip(array_keys($array1));
For example:
$array1 = array(
'a' => 123,
'b' => 567,
);
$array1_values = array_values($array1);
$array1_keymap = array_flip(array_keys($array1));
Value of $array1_values:
array(
0 => 123,
1 => 567,
);
Value of $array1_keymap:
array(
'a' => 0,
'b' => 1,
);
So:
$array1['a'] == $array1_values[$array1_keymap['a']];
$array1['b'] == $array1_values[$array1_keymap['b']];
Yes, as simple as
$array2 = $array1;
In this case you would get both values and keys like they are in the original array.
$keyMapping = array_combine(array_keys($array1), array_keys($array2));
This the keys of $array1 and maps them to the keys of $array2 like so
<?php
$array1 = array(
'a' => '1',
'b' => '2',
);
$array2 = array_values($array1);
print_r(array_combine(array_keys($array1), array_keys($array2)));
Array
(
[a] => 0
[b] => 1
)
You can use:
$array3 = array_keys($array1);
Now $array3[$n] is the key of the value in $array2[$n] for any 0 <= $n < count($array1). You can use this to determine which keys were in which places.
If you want to keep the same value of array1 but change the key to index numbers, try this:
$array2 = array();
foreach ($array1 as $key => $value){
$array2[] = $value;
// or array_push($array2, $value);
}
var_dump($array2);

Get array values by keys

I am searching for a built in php function that takes array of keys as input and returns me corresponding values.
for e.g. I have a following array
$arr = array("key1"=>100, "key2"=>200, "key3"=>300, 'key4'=>400);
and I need values for the keys key2 and key4 so I have another array("key2", "key4")
I need a function that takes this array and first array as inputs and provide me values in response. So response will be array(200, 400)
I think you are searching for array_intersect_key. Example:
array_intersect_key(array('a' => 1, 'b' => 3, 'c' => 5),
array_flip(array('a', 'c')));
Would return:
array('a' => 1, 'c' => 5);
You may use array('a' => '', 'c' => '') instead of array_flip(...) if you want to have a little simpler code.
Note the array keys are preserved. You should use array_values afterwards if you need a sequential array.
An alternative answer:
$keys = array("key2", "key4");
return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);
foreach($input_arr as $key) {
$output_arr[] = $mapping[$key];
}
This will result in $output_arr having the values corresponding to a list of keys in $input_arr, based on the key->value mapping in $mapping. If you want, you could wrap it in a function:
function get_values_for_keys($mapping, $keys) {
foreach($keys as $key) {
$output_arr[] = $mapping[$key];
}
return $output_arr;
}
Then you would just call it like so:
$a = array('a' => 1, 'b' => 2, 'c' => 3);
$values = get_values_for_keys($a, array('a', 'c'));
// $values is now array(1, 3)

where to use array() in PHP

can you give me examples of using array() function ?
There are plenty of examples in the manual:
http://php.net/manual/en/language.types.array.php
more specifically:
http://www.php.net/manual/en/function.array.php
$somearray = array();
$somearray[] = 'foo';
$somearray[] = 'bar';
$someotherarray = array(1 => 'foo', 2 => 'bar');
var_dump($somearray);
echo $someotherarray[2];
$a = array(1, 'test'=>2,'testing'=>'yes');
foreach($a as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
Even easier to see the output...
print_r($a);
$arr = array(1, 2, 3, 4, 5);
To loop over each element in the array:
foreach($arr as $val) {
print "$var\n";
}
One interesting thing to note about PHP arrays is that they are all implemented as associative arrays. You can specify the key if you want, but if you don't, an integer key is used, starting at 0.
$array = array(1, 2, 3, 4, 5);
is the same as (with keys specified):
$array = array(0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5);
is the same as:
$array = array('0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5);
Though, if you want to start the keys at one instead of zero, that's easy enough:
$array = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
Though if you don't specify the key value, it takes the highest key and adds one, so this is a shortcut:
$array = array(1 => 1, 2, 3, 4, 5);
The key (left side) can only be an integer or string, but the value (right side) can be any type, including another array or an object.
Strings for keys:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
Two easy ways to iterate through an array are:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
foreach($array as $value) {
echo "$value\n";
}
foreach($array as $key => $value) {
echo "$key=$value\n";
}
To test to see if a key exists, use isset():
if (isset($array['one'])) {
echo "$array['one']\n";
}
To delete a value from the array, use unset():
unset($array['one']);

Categories