spiltting an array into n arrays and accessing individual arrays in php - 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.

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.

How can I break preg_grep() in PHP?

I have 100 files named: file1, file2,file3... file100. I want to enter only 10 files in Array via preg_grep function, how can I limit the number?
$dir=glob('/mydir/*');
preg_grep('#file#i', $dir);
I get result array with length 100,how can I divide it before it create?
For PHP, to get the 1st 10 elements from the $dir array, use array_slice.
$dir=glob('/mydir/*');
$dir10 = array_slice($dir, 0, 10);
preg_grep('#file#i', $dir10);

How to limit string length in a multidimensional array?

I have a 2-dimensional PHP array containing strings ($fulltable) which I'm trying to fit into the datables grid (https://www.datatables.net/).
Sometimes some of the strings are really long. I'd like to truncate each string to lets say to 75 charachters, which will make the fields more manageable on display.
Is there an easy PHP function to do this or should I just create a double loop like this?
foreach ($fulltable as $row) {
foreach ($row as $field) {
// TRUNCATE FIELD HERE
}
}
You could use array_walk_recursive() to do this and take the value by reference, e.g.
array_walk_recursive($arr, function(&$v){
$v = substr($v, 0, 75);
});
Use mb_substr:
mb_substr($field, 0, 30);
Where 0 is the beginning and 30 is the end, 30 could be anything you want, the length of your output.
array_map() or array_walk() will apply a function to the contents of an array (single dimension), and be probably faster that looping with foreach.
There is also array_walk_recursive() for multi dimensional arrays.

Create a set of keys for an array

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), ""));

Splitting an array equally:

I have the following array:
$array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1);
I want split it up into individual arrays so that each array contains seven or less values.
So for example the first array will become:
$one = array(1,0,0,0,1,1,1)
$two = array(1,0,1,1,1,1,0)
$three = array(1,1,0,1,0,0,1);
$four = array(0,1);
Also how would you count the number of times 1 occurs in array one?
array_chunk() is what you are looking for.
$splitted = array_chunk($array, 7);
For counting the occurences I would be lazy. If your arrays only contain 1s or 0s, then a simple array_sum() would do:
print array_sum($splitted[0]); // for the first chunk
I want split it up into individual arrays so that each array contains seven or less values.
Use array_chunk(), which is made expressly for this purpose.
Also how would you count the number of times 1 occurs in array one?
Use array_count_values().
$one = array(1,0,0,0,1,1,1);
$one_counts = array_count_values($one);
print_r($one_counts);
// prints
Array
(
[0] => 3
[1] => 4
)
Assuming you want to preserve the contents of the array, I'd use array_slice() to extract the needed number of elements from the array, incrementing the '$offset' by the required count each time until the array was exhausted.
And as to your second question, try:
$num_ones=count(preg_grep(/^1$/,$array));

Categories