This question already has answers here:
php foreach as key, every two number as a group
(2 answers)
Closed 7 years ago.
How we can show the two elements in for each loop in each iteration?
For example I have an array like this:
$arr = array('a', 'b', 'c', 'd','e','f');
And want to show the records like this:
a-b
c-d
e-f
Any ideas?
You can use array_chunk, it is meant exactly for these kind of cases and it's the shortest and most efficient way to do it.
$arr = array('a', 'b', 'c', 'd','e','f');
foreach(array_chunk($arr , 2) as $val) {
echo implode('-', $val)."\n";
}
Chunks an array into arrays with size elements.
More details:
http://php.net/manual/en/function.array-chunk.php
Demo: https://3v4l.org/BGNbq
Loop over the array with for.
Print the current and current plus one value in each iteration by counter.
Increment the counter.
<?php
$arr = array('a', 'b', 'c', 'd','e','f');
$i=0;
$len = count($arr);
for ($i=0; $i< $len; $i++) { // We could have used count($arr)
//instead of $len. But, it will lead to
//multiple calls to count() function causing code run slowly.
echo "<br/>".$arr[$i] . '-' . $arr[$i+1];
++$i;
}
?>
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
?>
The above example will output:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
Try this:
<?php
$array = array('a', 'b', 'c', 'd','e','f');
$length = count($array);
for ($i=0; $i< $length; $i+2) {
echo "<br/>".$arr[$i] . '-' . $arr[$i+1];
}
?>
Related
This question already has answers here:
Create rows of elements based on an array of length values
(2 answers)
Closed 1 year ago.
I have a set of numbers which define the sizes of each chunk. How would I go about chunking an array based on these sizes?
For example, suppose I have the chunk sizes 2, 3 and 2, and an input array of size 7:
array(
0 => 'a',
1 => 'f',
2 => 'j',
3 => 'r',
4 => 'c',
5 => 'j',
6 => 'd',
)
I would like the first 2 elements from the above array to chunked into their own array, the next 3 to be chunked into their own array, and the last 2 to be chunked into their own array. This would procude the following output:
// first 2 elements:
array(
0 => 'a',
1 => 'f',
)
// next 3 elements:
array(
0 => 'j',
1 => 'r',
2 => 'c',
)
// last 2 elements:
array(
0 => 'j',
1 => 'd',
)
My actual input array has 64 elements and I want to chunk it based on the sizes 7, 9, 11, 16, 9 and 12 in that exact order.
You could make a function which partitions your array for you. You can first pass in the array, and then the chunks you require.
function partition($arr, ...$chunks) {
$res = [];
foreach($chunks as $n)
$res[] = array_splice($arr, 0, $n);
return $res;
}
$arr = ['a', 'f', 'j', 'r', 'c', 'j', 'd'];
print_r(partition($arr, 2, 3, 2));
The partitioning occurs by using array_splice(), which will change the array in-place. Each time array_splice() is called, you can grab the first $n elements from the array and push them into your result array. When you grab the first $n elements for a given chunk, you also remove them from the array.
Output:
Array
(
[0] => Array
(
[0] => a
[1] => f
)
[1] => Array
(
[0] => j
[1] => r
[2] => c
)
[2] => Array
(
[0] => j
[1] => d
)
)
See live example here
Loop through your data.
Keep current chunk count length in a variable.
Keep decrementing count and add all looped elements to a temp array.
If count reaches 0, add the current chunk(as in temp array) to result and move on to the next chunk.
Below code also works with irregular chunk size or data size.
Snippet:
<?php
$chunks_size = [7,9,11,16,9,12];
$data = ['a','f','j', 'r', 'c', 'j','d'];
$result = [];
$chunk_ptr = 0;
$count = $chunks_size[$chunk_ptr];
$temp = [];
foreach($data as $index => $val){
$count--;
$temp[] = $val;
if($count == 0){
$result[] = $temp;
$temp = [];
if(++$chunk_ptr == count($chunks_size)){
$count = PHP_INT_MAX; // Set it to a higher value or any negative value(all remaining goes into the last chunk)
}else{
$count = $chunks_size[$chunk_ptr];
}
}
}
if(count($temp) > 0) $result[] = $temp;
print_r($result);
Note: If $chunks_size is 0, you can throw an exception as it doesn't make sense to loop through all elements.
This question already has answers here:
PHP append one array to another (not array_push or +)
(11 answers)
Closed last month.
I have two arrays that are inside foreach loop, I want to merge them to one key and value.
let the first array "array1" inside foreach:
$array1 = ['x', 'y', 'z'];
let the second array "array2" inside foreach:
$array2 = ['a', 'b', 'c'];
Expected output should be as follows:
$mergeArray = [0=>['x', 'y', 'z','a', 'b', 'c']];
What I have done is the following:
$mergeArray = [];
foreach ($customer as $key => $value) {
$mergeArray[] = $value['items1'];
$mergeArray[] = $value['items2'];
echo '<pre>';
print_r($mergeArray);
exit;
}
Thanks and welcome all suggestions
Use array_merge:
$mergeArray[] = array_merge($value['item1'], $value['item2']);
Also, the exit should not be in the loop, that will prevent the loop from repeating.
You can do it with this code
$mergeArray = [];
foreach ($customer as $key => $value) {
$mergeArray[0] =array_merge ( $value['items1'], $value['items2']);
echo '<pre>';
print_r($mergeArray);
exit;
}
Why use a foreach loop at all? Am I missing something?
$array1 = array('x', 'y', 'z');
$array2 = array('a', 'b', 'c');
$mergeArray[0] = array_merge($array1, $array2);
Output:
Array
(
[0] => Array
(
[0] => x
[1] => y
[2] => z
[3] => a
[4] => b
[5] => c
)
)
Lets say we have two 2D array:
thisArray = array(
array('A', 'B', '');
array('A', 'B', '');
)
How to check is thisArrays arrays all have empty values at index 2 and if they do all have empty elements at index 2, how to remove those elements from all arrays?
I can't seem to figure this out and I can't seem to google out any php functions which would help me.
Using array_column(), and array_filter, you can achieve this,
array_column - gives you array in one direction
array_filter - filter, empty values,
So in the end if array is empty, then all are empty
<?php
$array = array(
array('A', 'B', ''),
array('A', 'B', '')
);
if(empty( array_filter(array_column($array,2))) ){
echo 'All are empty at index 2'.PHP_EOL;
// since all are empty
// use reference and unset
foreach($array as &$item) {
unset($item[2]);
}
// unset reference
unset($item);
}
print_r($array);
?>
Test Results:
$ php test.php
All are empty at index 2
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => Array
(
[0] => A
[1] => B
)
)
$thisArray = array(
array('A', 'B', '');
array('A', 'B', '');
)
Try this
foreach($thisArray as $array){
if(isset($array[2]) && $array[2]==null){ //if array at index 2 is empty
unset($array[2])); //remove array
}
}
return $thisArray;
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
?>
This example from php manual will output this:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
But i need to have an interval with fixed size. So the last value should be:
[2] => Array
(
[0] => e
[1] => null
)
Any idea?
$size = 3;
$input_array = array('a', 'b', 'c', 'd', 'e');
$result = array_chunk(
array_merge(
$input_array,
((count($input_array) % $size) == 0)
? array()
: array_fill(
0,
$size - (count($input_array) % $size),
NULL
)
),
$size
);
var_dump($result);
Don't know if this is the best practice, but it's how I would do it.
<?php
function arr_chunk($input_array, $chunk_size, $fixed=null) {
if (is_null($fixed)) {
$fixed = $chunk_size;
}
$chunked = array_chunk($input_array, $chunk_size);
for ($i = 0; $i < count($chunked); $i++) {
while (count($chunked[$i]) < $fixed) {
$chunked[$i][] = null;
}
}
return $chunked;
}
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(arr_chunk($input_array, 2));
?>
Where arr_array takes $fixed as an additional argument, or is set to $chunk_size giving all array chunks the same length.
I have an array which may contain numeric or associative keys, or both:
$x = array('a', 'b', 'c', 'foo' => 'bar', 'd', 'e');
print_r($x);
/*(
[0] => a
[1] => b
[2] => c
[foo] => bar
[3] => d
[4] => e
)*/
I want to be able to remove an item from the array, renumbering the non-associative keys to keep them sequential:
$x = remove($x, "c");
print_r($x);
/* desired output:
(
[0] => a
[1] => b
[foo] => bar
[2] => d
[3] => e
)*/
Finding the right element to remove is no issue, it's the keys that are the problem. unset doesn't renumber the keys, and array_splice works on an offset, rather than a key (ie: take $x from the first example, array_splice($x, 3, 1) would remove the "bar" element rather than the "d" element).
This should re-index the array while preserving string keys:
$x = array_merge($x);
You can fixet with next ELEGANT solution:
For example:
<?php
$array = array (
1 => 'A',
2 => 'B',
3 => 'C'
);
unset($array[2]);
/* $array is now:
Array (
1 => 'A',
3 => 'C'
);
As you can see, the index '2' is missing from the array.
*/
// SOLUTION:
$array = array_values($array);
/* $array is now:
Array (
0 => 'A',
1 => 'C'
);
As you can see, the index begins from zero.
*/
?>
I've come up with this - though I'm not sure if it's the best:
// given: $arr is the array
// $item is the item to remove
$key = array_search($item, $arr); // the key we need to remove
$arrKeys = array_keys($arr);
$keyPos = array_search($key, $arrKeys); // the offset of the item in the array
unset($arr[$key]);
array_splice($arrKeys, $keyPos, 1);
for ($i = $keyPos; $i < count($arrKeys); ++$i) {
if (is_int($arrKeys[$i])) --$arrKeys[$i]; // shift numeric keys back one
}
$arr = array_combine($arrKeys, $arr); // recombine the keys and values.
There's a few things I've left out, just for the sake of brevity. For example, you'd check if the array is associative, and also if the key you're removing is a string or not before using the above code.
Try array_diff() it may not order the new array correctly though
if not the following should work
You will need to iterate over it in the remove function.
function remove($x,$r){
$c = 0;
$a = array();
foreach ($x as $k=>$v){
if ($v != $r) {
if (is_int($k)) {
$a[$c] = $v;
$c++;
}
else {
$a[$k] = $v;
}
}
}
return $a;
}
DC
I don't think there is an elegant solution to this problem, you probably need to loop to the array and reorder the keys by yourself.