I have an array like:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
)
[2] => Array
(
[0] => d
[1] => e
[2] => f
)
)
I want to convert my array to a string like below:
$arrtostr = 'a,b,c,d,e,f';
I've used implode() function but it looks like it doesn't work on two-dimensional arrays.
What should I do?
Alternatively, you could use a container for that first, merge the contents, and in the end of having a flat one, then use implode():
$letters = array();
foreach ($array as $value) {
$letters = array_merge($letters, $value);
}
echo implode(', ', $letters);
Sample Output
Given your subject array:
$subject = array(
array('a', 'b'),
array('c'),
array('d', 'e', 'f'),
);
Two easy ways to get a "flattened" array are:
PHP 5.6.0 and above using the splat operator:
$flat = array_merge(...$subject);
Lower than PHP 5.6.0 using call_user_func_array():
$flat = call_user_func_array('array_merge', $subject);
Both of these give an array like:
$flat = array('a', 'b', 'c', 'd', 'e', 'f');
Then to get your string, just implode:
$string = implode(',', $flat);
You asked for a two-dimensional array, here's a function that will work for multidimensional array.
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
I can flatten an array structure like so:
$multidimensional_array = array(
'This',
array(
'is',
array(
'a',
'test'
),
array(
'for',
'multidimensional',
array(
'array'
)
)
)
);
echo implode_r(',', $multidimensional_array);
The results is:
This,is,a,test,for, multidimensional,array
Related
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;
If I have an associative array that is structured like
(
1 => 'a',
2 => 'b',
0 => 'c'
)
where all of the keys are numeric, will array_values ALWAYS guarantee that the values occur chronologically, in the new array, based on their previous keys' values, i.e. ['c', 'a', 'b']?
If not, how can I accomplish this instead?
No, array_values() will not reorder the values in any way. It doesn't care about keys.
Its effective implementation is basically this:
function array_values_impl(array $array)
{
$newArray = [];
foreach ($array as $item) {
$newArray[] = $item;
}
return $newArray;
}
If you want to sort the array using the keys, use ksort().
You can accomplish by first sorting the array with keys and getting values by array_values function.
For example
$array = array(
1 => 'a',
2 => 'b',
0 => 'c'
);
ksort($array);
print_r(array_values($array));
Output:
Array
(
[0] => c
[1] => a
[2] => b
)
I'm running a foreach loop on an array of students, that have a key ['all_user_grades']. What is the best way to count the number of As,Bs,Cs,Ds,Es and fails for each student in the array.
Here's what my array looks like:
[11] => Array
(
[id] => 10
[All_User_Grades] => A, A, D, A, E
)
Here's what my foreach looks like so far:
foreach($user_grades as $k => $v){
$aug = $v['All_User_Grades'];
$all_user_grades_arr = explode(',', $aug);
}
You can use the array_count_values() function:
$array = array('A', 'A', 'D', 'A', 'E');
$result = array_count_values($array);
print_r($result);
It outputs:
Array
(
[A] => 3
[D] => 1
[E] => 1
)
You can use substr_count() for this like so
$As = substr_count($aug, 'A');
$Bs = substr_count($aug, 'B');
//etc
or, just like you already did, explode and use the array for calculation
$all_user_grades_arr = explode(',', $aug);
$grades = array('A' => 0, 'B' => 0', ...);
foreach ($all_user_grades_arr as $val) {
$grades[ trim($val) ]++;
}
The trim() here is necessary to get rid of unnecessary whitespaces
You can try this way using array_count_values, i have used for single array, you change as per your requirements. See Demo http://ideone.com/YrGfPD
//PHP
$v=array('Id'=>10,'All_User_Grades'=>'A,A,D,A,E');
$aug = $v['All_User_Grades'];
$all_user_grades_arr = explode(',', $aug);
echo '<pre>';
print_r(array_count_values($all_user_grades_arr));
echo '</pre>';
//OUTPUT
Success time: 0.02 memory: 24448 signal:0
Array
(
[A] => 3
[D] => 1
[E] => 1
)
I know how to insert it to the end by:
$arr[] = $item;
But how to insert it to the beginning?
Use array_unshift($array, $item);
$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);
will give you
Array
(
[0] => item1
[1] => item2
[2] => item3
[3] => item4
)
In case of an associative array or numbered array where you do not want to change the array keys:
$firstItem = array('foo' => 'bar');
$arr = $firstItem + $arr;
array_merge does not work as it always reindexes the array.
Since PHP7.4 you can use the spread opperator, very similar to JavaScript
$arr = [$item, ...$arr];
https://wiki.php.net/rfc/spread_operator_for_array
A few more examples:
// Add an item before
$arr = [$item, ...$arr];
// Add an item after
$arr = [...$arr, $item];
// Add a few more
$arr = [$item1, $item2, ...$arr, $item3];
// Multiple arrays and and items
$arr = [$item1, ...$arr1, $item2, ...$arr2, $item3];
Note: this is only possible with int keys, not for associative arrays.
Note2: The keys are not kept.
BREAKING Example:
$car = ['brand' => 'Audi', 'model' => 'A8'];
$engine = ['cylinder' => 6, 'displacement' => '3000cc'];
$merged = [...$car, ...$engine];
var_dump($merged);
Will result in:
[ Error ] Cannot unpack array with string keys
For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
Insert an item in the beginning of an associative array with string/custom key
<?php
$array = ['keyOne'=>'valueOne', 'keyTwo'=>'valueTwo'];
$array = array_reverse($array);
$array['newKey'] = 'newValue';
$array = array_reverse($array);
RESULT
[
'newKey' => 'newValue',
'keyOne' => 'valueOne',
'keyTwo' => 'valueTwo'
]
There are two solutions:
if you have array with keys that matter to you
$new = ['RLG' => array(1,2,3)];
$array = ['s' => array(2,3), 'l' => [], 'o' => [], 'e' => []];
$arrayWithNewAddedItem = array_merge($new, $array);
if you have an array without any keys.
array_unshift(array, value1);
Use array_unshift() to insert the first element in an array.
Use array_shift() to remove the first element of an array.
Or you can use temporary array and then delete the real one if you want to change it while in cycle:
$array = array(0 => 'a', 1 => 'b', 2 => 'c');
$temp_array = $array[1];
unset($array[1]);
array_unshift($array , $temp_array);
the output will be:
array(0 => 'b', 1 => 'a', 2 => 'c')
and when are doing it while in cycle, you should clean $temp_array after appending item to array.