Is there a built-in function or otherwise elegant way of prefilling an array with a repeating pattern of values.
Essentially what I require is a combination of the array_fill and str_repeat.
I am going to say No. I have never come across anything like this. I think the best thing to do would be your own for-loop that appends values to array in the pattern that you need.
How about this:
function array_pattern($input_array, $repeat_count) {
$output_array=array();
for($count = 1; $count < $repeat_count; $count++) {
$output_array = array_merge($output_array,$input_array));
}
return $output_array;
}
(will only work for keyed array, not associative arrays, but the whole repeating pattern thing doesn't really lend itself to assoc arrays anyway)
Related
I have an array containing links. I am trying to cut a part of those links. For example:
$array = [
"https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
"https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular"
];
I want change these links like below:
array(2) {
[0]=>
string(91) "https://eksisozluk.com/merve-sanayin"
[1]=>
string(91) "https://eksisozluk.com/merve-sanayin"
[2]=>
}
Is there any possible way to edit array items?
Given the array:
$array = [
"https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
"https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular"
];
Using array_walk() (modifies the array in place).
Using a regular expression this time:
function filter_url(&$item)
{
preg_match('|(https:\/\/\w+\.\w{2,4}\/\w+-\w+)-.+|', $item, $matches);
$item = $matches[1];
}
array_walk($array, 'filter_url');
(See it working here).
Note that filter_url passes the first parameter by reference, as explained in the documentation, so changes to each of the array items are performed in place and affect the original array.
Using array_map() (returns a modified array)
Simply using substr, since we know next to nothing about your actual requirements:
function clean_url($item)
{
return substr($item, 0, 36);
}
$new_array = array_map('clean_url', $array);
Working here.
The specifics of how actually filter the array elements are up to you.
The example shown here seems kinda pointless, since you are setting all elements exactly to the same value. If you know the lenght you can use substr, or you could just could write a more robust regex.
Since all the elements of your input array are the same in the example, I am going to assume this doesn't represent your actual input.
You could also iterate the array using either for, foreach or while, but either of those options seems less elegant when you have specific array functions to deal with this kind of situation.
There are multiple ways. One way is to iterate over the items and clip them with substr().
$arr = array("https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular",
"https://eksisozluk.com/merve-sanayin-pizzaciya-kapiyi-ciplak-acmasi--5868043?a=popular");
for ($i = 0; $i < count($arr); $i++)
{
$arr[$i] = substr($arr[$i], 0, 36);
}
I'm not sure the title really gets across what I'm asking, so here's what I'm trying to do:
I have an array of arrays with four integer elements each, ie.
Array(Array(1,2,3,4), Array(4,2,3,1), Array(18,3,22,9), Array(23, 12, 33, 55))
I basically need to remove one of the two arrays that have the same values in any order, like indices 0 and 1 in the example above.
I can do this pretty easily when there are only two elements to check, using the best answer code in this question.
My multidimensional array can have 1-10 arrays at any given time, so I can't seem to figure out the best way to process a structure like that and remove arrays that have the same numbers in any order.
Thanks so much!
I've been thinking about this, and I think using a well designed closure with array_filter might be the way I'd go about this:
$matches = array();
$array = array_filter($array, function($ar) use (&$matches) {
sort($ar);
if(in_array($ar, $matches)) {
return false;
}
$matches[] = $ar;
return true;
});
See here for an example: http://ideone.com/Zl7tlR
Edit: $array will be your final result, ignore $matches as it's just used during the filter closure.
In regard to my question here, Jacob Relkin suggested a great solution of using call_user_func_array. That solved my problem but now I am really curious on how to do this in the absence of this function to achieve what I wanted in my original question which is below for reference:
Original Question:
I am creating an array of arrays in the following way:
$final_array = array();
for($i = 0; $i < count($elements); $i++) {
for($j = 0; $j < count($elements); $j++) {
if($i!=$j)
$final_array[] = array_intersect($elements[$i], $elements[$j]);
}
}
I am trying to find out the list of elements that occur in all the arrays inside the $final_array variable. So I was wondering how to pass this to array_intersect function. Can someone tell me how to construct args using $final_array[0], $final_array[1], ... $final_array[end_value] for array_intersect? Or if there is a better approach for this, that would be great too.
I am looking for a way to construct the following:
array_intersect($final_array[0], $final_array[1], $final_array[2], ...)
Well, the only real way to do this other than call_user_func_array would be to implode the resulting array into comma-separated arguments, then do something really really evil and use eval:
$args_imploded = implode(',', $some_array);
$result = eval('return array_intersect(' . $args_imploded . ')');
Why don't you just avoid the evil eval function and use the 'call_user_func_array' function? From what I understand about your code is that the $final_array parameter is an array of array's.
$result = call_user_func_array('array_intersect', $final_array);
No need for the eval function here.
EDIT: Stupid me. I didn't read your first paragraph properly ;). Please ignore this.
Starting with an array with 10K values. I want to randomly get 1000 values from it and put them into another array.
Right now, I am using a for loop to get the values, but I want to pick 1000 values and not have to loop 1000 times. The array_slice function works, but it doesn't give random values. What is the correct (most efficient) function for this task.
The code right now is
$seedkeys = (...array.....);
for ($i=0; $i<1000; $i++) {
$random = array_rand($seedkeys);
$randseed[$i] = $seedkeys[$random];
}//for close
TIA
Well, there are a few alternatives. I'm not sure which is the fastest since you're dealing with a sizable array, but you may want to try them out:
You can use shuffle, which will randomize the entire array. This will likely have the best performance since you're consuming a significant portion of the array (10%).
shuffle($seedkeys);
$result = array_slice($seedkeys, 0, 1000);
You could use array_rand (as you already said) in the manor that Tom Haigh specifies. This will require copying the keys, so if you're dealing with a significant portion of the source array, this may not be the fastest. (Note the use of array_flip, it's needed to allow the usage of array_intersect_key:
$keys = array_flip(array_rand($seedkeys, 1000));
$result = array_intersect_key($seedkeys, $keys);
If memory is tight, the best solution (besides the MySQL one) would be a loop since it doesn't require arrays to be copied at all. Note that this will be slower, but if the array contains a lot of information, it may offset the slowness by being more memory efficient (since it only ever copies exactly what it returns)...
$result = array();
for ($i = 0; $i < 1000; $i++) {
$result[] = $seedkeys[array_rand($seedkeys)];
}
You could do it in MySQL (assuming that the data for the array starts from MySQL). Be aware this is simple, but not that efficient (See Jan Kneschke's post)...
SELECT * FROM `foo` ORDER BY RAND() LIMIT 1000;
You could use array_rand() to get multiple items ?
$random_keys = array_rand($seedkeys, 1000);
shuffle($random_keys);
This will give you an array of random keys, so to get an array of values you need to do something like this:
$result = array();
foreach ($random_keys as $rand_key) {
$result[] = $seedkeys[$rand_key];
}
You could instead use array_intersect_key():
$result = array_intersect_key($seedkeys, array_flip($random_keys));
What's better to use in PHP for appending an array member,
$array[] = $value;
or
array_push($array, $value);
?
Though the manual says you're better off to avoid a function call, I've also read $array[] is much slower than array_push(). What are some clarifications or benchmarks?
I personally feel like $array[] is cleaner to look at, and honestly splitting hairs over milliseconds is pretty irrelevant unless you plan on appending hundreds of thousands of strings to your array.
I ran this code:
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
$array[] = $i;
}
print microtime(true) - $t;
print '<br>';
$t = microtime(true);
$array = array();
for($i = 0; $i < 10000; $i++) {
array_push($array, $i);
}
print microtime(true) - $t;
The first method using $array[] is almost 50% faster than the second one.
Some benchmark results:
Run 1
0.0054171085357666 // array_push
0.0028800964355469 // array[]
Run 2
0.0054559707641602 // array_push
0.002892017364502 // array[]
Run 3
0.0055501461029053 // array_push
0.0028610229492188 // array[]
This shouldn't be surprising, as the PHP manual notes this:
If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
The way it is phrased I wouldn't be surprised if array_push is more efficient when adding multiple values. Out of curiosity, I did some further testing, and even for a large amount of additions, individual $array[] calls are faster than one big array_push. Interesting.
The main use of array_push() is that you can push multiple values onto the end of the array.
It says in the documentation:
If you use array_push() to add one
element to the array it's better to
use $array[] = because in that way
there is no overhead of calling a
function.
From the PHP documentation for array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
Word on the street is that [] is faster because no overhead for the function call. Plus, no one really likes PHP's array functions...
"Is it...haystack, needle....or is it needle haystack...ah, f*** it...[] = "
One difference is that you can call array_push() with more than two parameters, i.e. you can push more than one element at a time to an array.
$myArray = array();
array_push($myArray, 1,2,3,4);
echo join(',', $myArray);
prints 1,2,3,4
A simple $myarray[] declaration will be quicker as you are just pushing an item onto the stack of items due to the lack of overhead that a function would bring.
Since "array_push" is a function and it called multiple times when it is inside the loop, it will allocate memory into the stack.
But when we are using $array[] = $value then we are just assigning a value to the array.
Second one is a function call so generally it should be slower than using core array-access features. But I think even one database query within your script will outweight 1000000 calls to array_push().
See here for a quick benchmark using 1000000 inserts: https://3v4l.org/sekeV
I just wan't to add : int array_push(...) returns
the new number of elements in the array (PHP documentation). which can be useful and more compact than $myArray[] = ...; $total = count($myArray);.
Also array_push(...) is meaningful when variable is used as a stack.