Create a set of keys for an array - php

So I make an API call. This generates an array with dynamic number of elements. I want to add additional empty keys until the number of elements reach 50 (api call will always be lesser than 50). What is the easiest way to do this? Currently I am doing:
$dataArray = $this->APICall();
$toAdd = 50 - count($dataArray);
for($x=$toAdd;$x<=50;$x++)
{
$dataArray[$x] = "";
}
I wanted to check if there is an easier, perhaps single-line way of doing this...

There is function array_fill that you can use to fill array with spaces to size of 50. And then merge it with initial array.
Documentation for array_fill is here
$dataArray = array_merge($dataArray, array_fill(count($dataArray), 50 - count($dataArray), ""));

Related

Explode Array and Show 4 random items at a time with Shuffle

I am trying to explode an array and then shuffle 4 items at a time so that each array appears in random order.
It half works but on refresh sometimes it shows only 2 or 3 arrays not 4. Is there an easy workaround for it?
Thanks in advance.
$siteswith = $row['siteswith'];
$array = explode(',', $siteswith);
shuffle($array);
foreach(array_slice($array, 0, 4) as $item ){
}
It seems that $array does not have enough items that the slice function can "slice" from. Please check if your input string $row['siteswith'] always provide 4 or more comma separated values.
Depending what the code is later used for, you could also use array_rand() to pick n random elements from the list
$siteswith = $row['siteswith'];
$array = explode(',', $siteswith);
foreach(array_rand($array, 4) as $item ){
...
}
This will also prevent mutating your origin array (other than array_shift will do) which avoids unexpected behaviour.
Please be aware that you'll receive an exception when the array size is smaller than the requested amount of random elements.

Resorting integers in PHP to remove gaps

I'm searching for an algorithm to remove gaps between numbers. Example of my problem:
Here is a range of integers: [1,2,3,4,9,10,11,17...]
I need to make those numbers like this: [1,2,3,4,5,6,7,8...]
Can anyone provide me with a working example of PHP code to obtain such a result?
You should fetch min and max from an array and create the range,
$min = min($arr);
$max = max($arr);
print_r(range($min,$max));
You can make by using range function as:
// given array 2,4,6 and 9 are missing.
$arr1 = array(1,3,5,7,8,10);
// construct a new array using range function by giving min(given array) and max(given array) value
$arr2 = range(min($arr1),max($arr1));

I want to make custom array shuffle in php with respect to integer

Looking the function below:
function CustomShuffle($arr, $para){
............................
............................
return $array;
}
Suppose this is an array:
$array = array("red","green","blue","yellow","purple");
looking output something like below (May be different ordered but must be same for same integer parameter)
$result = CustomShuffle($array, 10);
// output: array("blue","purple","yellow","red","green") same
$result = CustomShuffle($array, 12);
// output: array("purple","yellow","red","green","blue")
$result = CustomShuffle($array, 10);
// output: array("blue","purple","yellow","red","green") same
$result = CustomShuffle($array, 7);
// output: array("blue","yellow","purple","red","green")
Simply, array will be shuffled with respect to integer parameter but output will be same for same parameter. Is it possible?
Yes this is possible, how it happens does come down to a desired implementation and how many permutations you wish to allow. A very naive method of accomplishing this is to have a loop that runs $para times within CustomShuffle that would array_shift() an element then array_push() that same element. This method would only give you count($array) possible outcomes, meaning numbers congruent modulo count($array) would produce the same result.
The optimal algorithm would allow you to take advantage of the maximum combinations, which would be gmp_fact(count($array)), or simply the factorial of the length of the input array. There is no possible way to achieve more unique combinations than this value, so no matter what algorithm you design, you will always have a constraint on the value of $para until you eventually encounter a combination already seen.

spiltting an array into n arrays and accessing individual arrays in php

I have an array of 1000 emails.
And I want to split the array into n arrays having 45 emails in each array.
I want to separately access the splitted arrays.
How can we implement using php. I have also tried array_splice() function in php, but it returns splitted arrays, but I unable to access the splitted array.
You could use array_chunk() in this case to get batches of those emails:
$emails = array('email1', 'email2', ..... 'email1000');
// 45 each batch
$batch_emails = array_chunk($emails, 45);
foreach($batch_emails as $batch) {
print_r($batch);
}
// or explicitly get batch/group 5
print_r($batch_emails[4]);
try this -
$f = array_chunk($yourArray, 45);
var_dump($f);
Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

Limit array to 5 items

I have a code that will add a number to an array each time a page is visited. the numbers are stored in a cookie and are retrieved later.
I would like to keep only the 5 most recent numbers in the array.
if the array is full (5 items) and a new number must be added, then the oldest number must be removed and the most recent items must be kept
here's what i have:
$lastviewedarticles = array();
if (isset($_COOKIE["viewed_articles"]) ) {
$lastviewedarticles = unserialize($_COOKIE["viewed_articles"]);
}
if (!in_array($articleid, $lastviewedarticles)){
$lastviewedarticles[] = $articleid;
}
setcookie("viewed_articles", serialize($lastviewedarticles));
array_slice returns a slice of an array
array_slice($array, 0, 5) // return the first five elements
use array_splice and array_unique to get the 5 unique array values
array_splice(array_unique($lastviewedarticles), 0, 5);
First of all i think, you need to obtain array length , then if length > or equal to 5, remove first element , and add element to the end of array.
if (!in_array($articleid, $lastviewedarticles)){
$count = count($lastviewedarticles);
if($count>=5)
array_shift($lastviewedarticles);
$lastviewedarticles[] = $articleid;
}
Use a counter to access the array, increment it in every call and use the modulus operation to write into the array. If your counter has to persist over several calls you have to store it in a session variable or a cookie.
Assuming that $i holds your counter variable this would look like
if (!in_array($articleid, $lastviewedarticles)){
$lastviewedarticles[$i%5] = $articleid;
$i++;
}
The result is a primitive ring buffer that will always contain the last 5 values.

Categories