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
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
)
)
I want to merge the keys of array based on values. This is my array.
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 0
[6] => 2
[7] => 2
)
I want output as
Array
(
[1,2,3] => 1
[4,6,7] => 2
[5] => 0
)
I have been brain storming entire day but couldn't find a solution. Any hint would be much appreciated.
WHAT I HAVE TRIED:
for($i=2;$i<=count($new);$i++){
if ($new[$i-1][1]==$new[$i][1]){
$same .= $new[$i-1][0].$new[$i][0];
}
}
echo $same;
But I am stucked. I am comparing the keys one by one but it's very complicated. I don't need the code. I only need the hint or logic. Anyone kind enough?
<?php
$old_arr = ["1"=>1,"2"=>1,"3"=>1,"4"=>2,"5"=>0,"6"=>2,"7"=>2];
$tmp = array();
foreach($old_arr as $key=>$value)
{
if(in_array($value, $tmp)){
$index = array_search($value, $tmp);
unset($tmp[$index]);
$tmp[$index.",".$key] = $value;
}else{
$tmp[$key] = $value;
}
}
ksort($tmp);
echo "<pre>";
print_r($tmp);
echo "</pre>";
?>
https://eval.in/529314
You can loop through array elements and create a new array with new structure. Please check the below code it may help you
$old_array = array(1=> 1,2 => 1,
3=> 1,
4 => 2,
5 => 0,
6 => 2,
7 => 2
);
$new_array = array();
foreach($old_array as $key => $value)
{
if(in_array($value,$new_array))
{
$key_new = array_search($value, $new_array);//to get the key of element
unset($new_array[$key_new]); //remove the element
$key_new = $key_new.','.$key; //updating the key
$new_array[$key_new] = $value; //inserting new element to the key
}
else
{
$new_array[$key] = $value;
}
}
print_r($new_array);
$arr = array(1 => 1, 2 => 1, 3 => 1, 4 => 2, 5 => 0, 6 => 2, 7 => 2);
$tmp = array();
foreach ($arr as $key => $val)
$tmp[$val][] = $key;
$new = array();
foreach ($tmp as $key => $val)
$new[implode(',', $val)] = $key;
First loop the original array through, creating a temporary array, where your original values are keys and values are the original keys as an array.
Then loop the temporary array, creating the new array, where the temporary array's values are imploded as keys.
There's no way to have an array of keys to a single value, but the other way around:
function flipWithKeyArray($arr){
$result = array();
foreach($arr as $key => $val){
if(!isset($result[$val]))
$result[$val] = array();
$result[$val][] = $key;
}
return $result;
}
This will flip your array and declare one array per value of your old array and then push the keys with the same value into each list.
For an array like this:
array(1=>1, 2=>1, 3=>1, 4=>2, 5=>2, 6=>2)
The result will look like this:
array(1=>array(1,2,3), 2=>array(4,5,6))
Hope it fits your need.
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 multi-dimensional array where I'm trying to output an integer value for the keys in the second array (sub array).
My array is pretty basic, like this:
$array = array(
array(
'a' => 'd',
'b' => 'e',
'c' => 'f'
),
array(
'a' => 'x',
'b' => 'y',
'c' => 'z'
),
);
So when I create a foreach for that array...
foreach ( $array as $array_key => $sub_array ) {
foreach ( $sub_array as $key => $value ) {
echo $key;
}
}
I output $key in the sub-loop and that just returns the array's key values, which are a, b, c - a, b, c
How can I actually get the integer value or position of those key values in the sub-array? So for each grouping in the array, a would be 1, b would be 2, c would be 3. Then it would start over for the next grouping in the array.
I've tried using $int++; but that applies to both groups in the array, resulting in it going from 1-6, instead of 1-3, 1-3, etc.
Could something with array_keys work on this? Any help, as always, would be hugely appreciated!
Try this code.
foreach ( $array as $array_key => $sub_array ) {
$i = 1;
foreach ( $sub_array as $key => $value ) {
echo $i . ' - ' $key . ' ';
$i++;
}
}
This will give you an expected result.
1 - a 2 - b 3 - c 1 - a 2 - b 3 - c
And if you use the this code below.
$i = 1;
foreach ( $array as $array_key => $sub_array ) {
foreach ( $sub_array as $key => $value ) {
echo $i . ' - ' $key . ' ';
$i++;
}
}
This is the result.
1 - a 2 - b 3 - c 4 - a 5 - b 6 - c
Which is the output you encountered, not you expect. Note the location of the variable $i.
I am trying to add a key=>value pair to an array while using a foreach loop, when that value is added the foreach loop needs to process the new key=>value pair.
$array = array(
'one' => 1,
'two' => 2,
'three' => 3
);
foreach($array as $key => $value) {
if ($key == 'three') {
$array['four'] = 4;
} else if ($key == 'four') {
$array['five'] = 5;
}
}
If I print the array after the loop, I would expect to see all 5 kv's, but instead I only see this:
Array
(
[one] => 1
[two] => 2
[three] => 3
[four] => 4
)
Is there some way, when I add the fourth pair, to actually process it so the fifth pair gets added within that foreach loop (or another kind of loop?)
According to php documentation,
As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.
You cannot modify the array during foreach. However, an user posted an example of a regular while loop that does what you need: http://www.php.net/manual/en/control-structures.foreach.php#99909
I report it here
<?php
$values = array(1 => 'a', 2 => 'b', 3 => 'c');
while (list($key, $value) = each($values)) {
echo "$key => $value \r\n";
if ($key == 3) {
$values[4] = 'd';
}
if ($key == 4) {
$values[5] = 'e';
}
}
?>
the code above will output:
1 => a
2 => b
3 => c
4 => d
5 => e
That's because PHP will internally use it's own copy of the array pointer. You are iterating trough it's orginal key/values not through the modified array.
As the original array contains the key three, the first if statement will match, but not the second
Another simpler example is the fact, that this is not an infinite loop:
$array = array(1);
foreach($array as $val) {
$array []= $val +1;
}
var_dump($array);
Output:
array(2) {
[0] =>
int(1)
[1] =>
int(2)
}
However, the PHP documentation says not much to that:
As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.