PHP: Associate array index name in a foreach loop - php

I can get the index number from a foreach loop by doing the following.
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// gives me "1: $row etc
}
If my array is associative is there away to get the associative name instead of the index number into my loop?

Actually you allready did it:
$associativeArray = array(
'First' => 1,
'Second' => 2,
'Third' => 3,
);
foreach ($associativeArray as $index => $value) {
echo $index . ": " . $value;
}
// First: 1
// Second: 2
// Third: 3

<?
$rows = array();
$rows['hi'] = 'there';
$rows['foo'] = 'bar';
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// $index will be hi and foo
}
?>
PHP arrays ARE associative where regular arrays just have integers as keys.
The PHP documentation actually mentions this in the first sentence: http://php.net/manual/en/language.types.array.php
An array in PHP is actually an ordered map..
PHP doesn't have arrays, it has maps/dictionaries that are called arrays but they are not arrays like in other languages.

Related

Compare all value of two array in one foreach

I've 2 array in php
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
This is a result of select query wrote in codeigniter. so that is associative array. This is 2 query result one is for user list and second is for invited user list. I want check in user list which user is invited. So that I want to compare that array
foreach ($array1 as $key => $value) {
if($array2[$key]->invite_user_id==$value->user_id) {
echo "Matched";
}
}
but it compare only 2 value of array1 with array2 3rd value is not compare. How it could compare all value of array1 and array2 in above foreach loop
I found that answer
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
$invitationset = [];
foreach ($array2 as $invite) {
$invitationset[$invite->invite_user_id] = $invite->invite_user_id;
}
foreach ($array1 as $key => $value) {
if(isset($invitationset[$value->user_id])){
if($invitationset[$value->id]==$value->user_id){
echo "Matched";
}
}
}
In your assoc arrays you have dublicate keys. So if you use:
print_r( $array1 );
You'll see that your array only contains the last entry:
Array ( [user_id] => 3 )
I think that is not what you have expected. So you have to use different keys like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
Or you even dont use assoc arrays because it is obsolete in your example but never mind:
$user_ids = array('1','2','3');
$invited_user_ids = array('1','3');
You can compare your assoc arrays like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
foreach ($array1 as $user_id) {
if( in_array( $user_id, $array2 ) ) {
echo "Matched id: $user_id";
}
}

Combine 2 Arrays In Foreach in PHP

I would like to combine these two foreach statements together. I've seen a few solutions around here, but nothing really works for me.
This is my username list from database.
$digits = [1,2,3,4];
$results = $db->table($usernames)
->where('memberID', $mID)->limit(10)
->getAll();
foreach ($results as $result) {
echo $result->userName;
}
I tried this:
$combined = array_merge($digits, $results);
foreach (array_unique($dogrularVeSiklar) as $single) : { ?>
{
echo $single.'<br>';
echo $results->userName;
},
}
You don't show what $dogrularVeSiklar is or where you get it, but as an example; combine into $key => $value pairs and foreach exposing the key and value:
$combined = array_combine($digits, $results);
foreach ($combined as $digit => $result) {
echo $digit . '<br>' . $result;
}
foreach operates on only one array at a time.
The way your array is structured, you can use array_combine() function to combine them into an array of key-value pairs then foreach that single array

SELECT array from mysql table and print

I have a column in my table that contain an array like:
1,4,2,8,4,5,7
How to select these numbers and print them separately?
Item: 1
Item: 4
Item: 2
Item: 8
Item: 4
Item: 5
Item: 7
What I have tried:
$result = mysql_query('SELECT * FROM test');
$arr = array();
while(($row = mysql_fetch_array($result))) {
$arr = array_merge($arr , explode(',', $row['item']));
echo "Item: " . $arr . "<br>";
}
Result:
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Item: Array
Can anyone help me?
Your biggest problem is trying to echo the whole array at once rather than echoing an index of the array at a time.
Unless you plan on using all the rows again after the while loop, you don't need the array_merge so take that out. What you need is a foreach inside the while loop to loop through the array created by explode.
while(($row = mysql_fetch_array($result)))
{
$arr = explode(',', $row['item']);
foreach ($arr as $key => $value)
{
echo "Item [$key]: " . $value . "<br>";
}
}
(And you really should switch off of mysql_ to PDO or mysqli_ since mysql_ is deprecated.)
try:
$arr = explode(',', $row['item']);
foreach($arr as $single){
echo "item: $single";
}
You are almost there. I hope this gives the result you expect. In your question it is not quite clear how exactly the data is stored.
If all the data is in one row, this will do it:
$result = mysql_query('SELECT item FROM test');
$arr = array();
$row = mysql_fetch_array($result);
$arr = explode(',', $row['item']);
foreach ($arr as $item) {
echo "Item: " . $item . "<br>";
}

How to access elements inside MultiDimensional Array in php

How to access all the elements under each key of multidimensional array.
$multi = array
(
"Abhishek" => array("Choudhary", "Bunta", "Popy"),
"Bond" => array("One", "two", "three", "four"),
"Super" => array("T1", "T2")
);
$data = array("Abhishek","Bond","Super");
for($j = 0;$j<count($data);$j++)
{
echo "<br/>Main Array Value ".$data[$j]."<br/>";
for($i = 0;$i<count($data[$j]);$i++)
{
echo "sub Value ".$multi[$data[$j]][$i]." count ".count($data[$j]) ;
}
}
Now I want to iterate through each element of Abhishek , Bond and Super , so we can see Abhishek has 3 elements inside it but $data[$j] always return 1. If I increment then I can access Bunta
Currently the output is -
Main Array Value Abhishek
sub Value Bunta
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
and expected is:
**
Main Array Value Abhishek
sub Value choudhary
sub Value Bunta
sub Value Popy
:
:
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
**
Disclaimer : I am super new to PHP so may be my expectation can be invalid or I am missing some very silly thing.
i recommend you read some articles about multidim arrays, anyway your needs could be done with following code:
foreach($multi as $key => $value) {
echo "<br/>Main Array Value ".$key."<br/>";
for($i = 0; $i < sizeof($value); $i++) {
echo "sub Value ".$value[$i]." count ".sizeof($value) ;
}
}
PS: you don't need $data array
#bunta please check this out: PHP Foreach
You could use foreach instead.
Also:
PHP foreach loop through multidimensional array
HTH.
Using foreach() would be easier
foreach ($multi as $key => $subarray)
{
echo $key . '<br />';
foreach ($subarray as $subvalue)
{
echo ' - '.$subvalue . '<br />';
}
}
Will output
Abhishek
- Choudhary
- Bunta
- Popy
Bond
- One
- two
- three
- four
Super
- T1
- T2
Try this :
<?php
foreach($multi as $key => $value) {
echo "<br/>Parent Value ".$key."<br/>";
for($i = 0; $ < sizeof($value); $++) {
echo "Child Value ".$value[$i]." count ".sizeof($value) ;
}
}
?>
You are using wrong syntax to access it.
Thanks
All you need is use foreach to iterate on $multi array (if you just want to know the number of subelements for each element level 1):
<?php
echo "<br\>multiDimensional Array<br\>";
$multi = array("Abhishek" =>array
("Choudhary",
"Bunta",
"Popy"),
"Bond" => array
("One",
"two",
"three",
"four"),
"Super" => array
("T1",
"T2")
);
foreach( $multi as $value ){
echo " count ".count($value) ;
}

Display array_key from PHP array?

Here I am Having an Issue:
I have two arrays like the following:
$array1 = array('1','2','1','3','1');
$array2 = array('1','2','3'); // Unique $array1 values
with array2 values i need all keys of an array1
Expected Output Is:
1 => 0,2,4
2 => 1
3 => 3
here it indicates array2 value =>array1 keys
Just use a loop:
$result = array();
foreach ($array1 as $index => $value) {
$result[$value][] = $index;
}
If you pass array_keys a 2nd parameter, it'll give you all the keys with that value.
So, just loop through $array2 and get the keys from $array1.
$result = array();
foreach($array2 as $val){
$result[$val] = array_keys($array1, $val);
}
The following code will do the job. It will create a result array in which the attribute val will contain the value that is searched in array and keys attribute will be an array that contains the found keys. Based on your values following is an example:
$array1 =array('1','2','1','3','1');
$array2 =array('1','2','3');
$results = array();
foreach ($array2 as $key2=>$val2) {
$result = array();
foreach ($array1 as $key1=>$val1 ) {
if ($val2 == $val1) {
array_push($result,$key1);
}
}
array_push($results,array("val"=>$val2,keys=>$result ));
}
echo json_encode($results);
The result will be:
[{"val":"1","keys":[0,2,4]},
{"val":"2","keys":[1]},
{"val":"3","keys":[3]}]

Categories