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
)
)
Related
This question already has answers here:
How to loop through an associative array and get the key?
(12 answers)
Closed 5 years ago.
I would like to get the index of the current element of an array in a loop.
If I have this exemple :
<?php
$array = array('a', 'b', 'c', 'd', 'e');
foreach($array as $elem)
{
echo $elem;
}
>
How could I get the index of elem in this loop (ex: 1 for 'b') ?
I tried current($array) but the return value stay at 0 in my loop but with print_r() I have this.
print_r($array);
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )
Have you got any idea ?
if you want all keys in an array, you can use array_keys() function.
If you want to check a key does exist in your array or not, use array_key_exists() function like:
array_key_exists ( $key , $array );
or you simply want to access your keys, use foreach() like:
foreach($array as $key => $value){
echo 'Key = '.$key.' , Value = '.$value;
}
Try this;
foreach ($array as $key => $value) {
echo $key; //<- for testing
if($value==mayval)echo "The key is $key";
}
Use foreach ($array as $k => $v)
<?php
$array = array('a', 'b', 'c', 'd', 'e');
foreach($array as $k => $v) {
echo $k . ' => ' . $v . PHP_EOL;
}
Output:
0 => a
1 => b
2 => c
3 => d
4 => e
https://eval.in/772092
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];
}
?>
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 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
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.