Create associative array from numeric array and function? - php

I have a numeric array with codes like this: array('123', '333', '444');
I also have a function that given a code returns a name, so myFunc('123') would return 'soap'
I'd like to generate an associative array containing codes as keys and names as values. Is there any function that would allow me to do this? I know a foreach loop would do it but I wonder if there's some made function for this. Saw some methods like array_map but they don't seem to fit my needs.

array_combine($arr, array_map('myFunc', $arr))
But two functions, not one ;-) Still oneliner though

Related

PHP Cleaning up nested arrays with unknown structure

Let's assume I have an array like so:
[1=>[1=>2,2=>"something"],2=>[1,2],3=>"hello"]
The array has a "unorganized" structure with subarrays other values.
I want to run a htmlentities function on each value to make sure nothing bad is inside the values.
I've been reading up on RecursiveIteratorIterator but I cannot find an example of how to use it to apply a function to each value in a quite random nested multidimensional array. Any help is appreciated.
You could simply make use of array_walk_recursive:
array_walk_recursive($input, function (&$value) {
$value = htmlentities($value);
});
Demo: https://3v4l.org/QmRJr

php sort associative arrays by keys that those keys exist in other array

I have this array
$myArray=array(
'a'=>array('id'=>1,'text'=>'blabla1'),
'b'=>array('id'=>2,'text'=>'blabla2'),
'c'=>array('id'=>3,'text'=>'blabla3'),
'd'=>array('id'=>4,'text'=>'blabla4'),
);
and i want to sort the above array by the keys a,b,c,d, who exist in another array:
$tempArray=array('c','a','d','b');
How can I do that so the $myArray
looks like this:
$myArray=array(
'c'=>array('id'=>3,'text'=>'blabla3'),
'a'=>array('id'=>1,'text'=>'blabla1'),
'd'=>array('id'=>4,'text'=>'blabla4'),
'b'=>array('id'=>2,'text'=>'blabla2'),
);
thanks for helping me!
The simplest and likely most efficient way to do this is by iterating the array that holds the sort order and creating a new, sorted array:
$sorted = array();
foreach ($tempArray as $order) {
if (isset($myArray[$order])) {
$sorted[$order] = $myArray[$order];
}
}
print_r($sorted);
This works because associative arrays implicitly have an order of the order in which elements were added to the array.
See it working
EDIT
Any solution involving a sorting function will likely be much less efficient than this. This is because in order to do it you will need to use a function that takes a callback - this already has an implied overhead of the function call.
The sorting functions also work by comparing items, meaning that the complexity any of those solutions will be greater than that of this solution (the complexity of this is simply O(n)). Also, in order to derive the return value for the sorting function you would need to inspect the target array, finding the position of each of the keys being compared, for each comparison, adding even more complexity.

Creating an associative array from an array, based on the array - PHP

I have a unique issue that I have never heard of this being possible to do before:
So essentially I have a function that takes in a an array of arguments such as:
function someFunction(array $arguments){}
and gives me an array back as such:
array('option1', 'option2', 'options3', ...);
I then need to take that array and loop through it creating an associative array such as:
array('option1' => call_come_method('option1'), .... );
heres the kicker, you will never know how many arguments a user passes into the function, yet each one needs to created into a key=>value arrangement as seen above.
Now i did some research and I was told the $argv command in php, how ever where I am stumped is how to implement it in this case.
So if any one can give me any pointers I would be appreciative.
This is a lot easier than you think. First use array_flip to switch the array's keys and values.
$newArray = array_flip($arguments);
Then loop though it and call the method:
foreach($newArray as $key=>&$val){
$val = call_come_method($key);
}
The &, makes it a reference, so the array value is updated.
DEMO: http://codepad.org/giL1KPA3
UPDATE: You don't even need array_flip, you just need a for loop.
$newArray = array();
foreach($arguments as $val){
$newArray[$val] = call_come_method($val);
}
DEMO: http://codepad.org/AQ1gWrou
you will never know how many arguments a user passes into the function
FYI, you get to know it with func_get_args().
This way you don't need to provide your function with an $arguments parameter, but you just leave it empty.

Can't flatten multidimensional array with lots of duplicates

I'm trying to create a script that, based on an input a?? creates an array of all the combinations and permutations of all words containing an a and two other characters from the alphabet.
Values are such as a, ab, ba, dab, bga etc - as you may see the array contains (or should contain) a weird amount of values.
The problem is that the functions I use in the script outputs even more values with many duplicates.
And for some reason I can not create a flattened array without duplicates. I tried to use array_unique() but it doesn't work here. I tried to use explode() and implode() to flatten the result array, but no success. Even if I succeed to create a string from the values, when I try to transform this string into an array, the result is again the actual multi-dimensional array.
This drives me crazy, and as you see the code, I'm a beginner in PHP.
Any help to transform the actual multidimensional array to a flattened one without duplicates is highly appreciated. An example: actually the array contains 12168 sub-arrays, and only the string a occurs 1456 times. What I need is an array that doesn't have sub-arrays and contains each results only one time.
The PHP code is available at here
and the output is here:
Have you tried something like:
$inputString = 'a??';
$array = array();
if (strpos($inputString, 'a') !== false && !in_array($inputString, $array)) {
$array[] = $inputString;
}
echo '<pre>'; print_r($array); echo '</pre>';

Get arbitrary number of random elements from a php array in one line

I wanted to pull an arbitrary number of random elements from an array in php. I see that the array_rand() function pulls an arbitrary number of random keys from an array. All the examples I found online showed then using a key reference to get the actual values from the array, e.g.
$random_elements = array();
$random_keys = array_rand($source_array);
foreach ( $random_keys as $random_key ) {
$random_elements[] = $source_array[$random_key];
}
That seemed cumbersome to me; I was thinking I could do it more concisely. I would need either a function that plain-out returned random elements, instead of keys, or one that could convert keys to elements, so I could do something like this:
$random_elements = keys_to_elements(array_rand($source_array, $number, $source_array));
But I didn't find any such function(s) in the manual nor in googling. Am I overlooking the obvious?
What about usung array_flip? Just came to my mind:
$random_elements = array_rand(array_flip($source_array), 3);
First we flip the array making its values become keys, and then use array_rand.
An alternate solution would be to shuffle the array and return a slice from the start of it.
Or, if you don't want to alter the array, you could do:
array_intersect_key($source_array, array_combine(
array_rand($source_array, $number), range(1, $number)));
This is a bit hacky because array_intersect can work on keys or values, but not selecting keys from one array that match values in another. So, I need to use array_combine to turn those values into keys of another array.
You could do something like this, not tested!!!
array_walk(array_rand($array, 2), create_function('&$value,$key',
'$value = '.$array[$value].';'));

Categories