I'm try to using array in PHP by finding it index and keys as foreach.
example I want to get $k["ab"] or $ro["hh"] but I can't get it
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
var_dump($k);
}
?>
You'd better learn the structure of multi-dimensional array.
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $key => $values){
echo $key; // which will output "test", "ab", which are the array keys
print_r($values); // which will output the contents of the inner array (e.g. array("some"=>"d","hello"=>"e","ther"=>"a") )
// to obtain the inner array values, you can either use another foreach...
foreach($values as $k => $v) {
echo $k . ', ' . $v; // which will output "ad, tt", etc
}
// ...or specify which key to obtain
if(isset($values["ad"])) { echo $values["ad"]; }
// isset() must be used, as the key does not exist in 1st inner array
}
?>
Please try Below :
<?php
$data = array(
"test"=>array(
"some"=>"d",
"hello"=>"e",
"ther"=>"a"
),
"ab"=>array(
"ad"=>"tt",
"de"=>"jj",
"hh"=>"uu")
);
foreach($data as $k=>$ro){
if($k == "ab"){
echo "<pre>";
print_R($ro);
echo 'HH Value ===> '.$ro['hh'];
}
}
?>
And Want to get All values and Keys Try Below For Each :
foreach($data as $k=>$ro){
foreach($ro as $inner_key => $inner_value){
echo "<br/> Key ===> ".$inner_key."==== value =====>".$inner_value;
}
}
Related
My array which is dynamic, formed as
$exam = explode(',',$row['exam']);
For example result is:
$exam = array("First-Term","Second-Term", "Third-Term");
We can get index and value as this
foreach (array_values($exam) as $i => $value) {
echo "$i: $valuen";
echo "//And its mark";
}
But, how can I break loop to each index. I have to fetch as follow
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
But while using foreach loop, I am getting
First-Term
Second-Term
Third-Term
//And its mark
//And its mark
//And its mark
How to break loop to each index, after that we use same code in every index. I'm simply try to assign each marks to each term
$exam[0]{
//here is $value
//rest of the code, same code to every index
}
$exam[1]{
//here is $value
//rest of the code, same code to every index
}
$exam[2]{
//here is $value
//rest of the code, same code to every index
}
$exam[...]{
//
}
You should make two arrays for team and marks and then parse these two arrays in the same foreach loop like this
$team = array('a', 'b', 'c', 'd' );
$marks = array('1', '2', '3', '4' );
foreach(array_combine($team, $marks) as $t => $m) {
echo $t . "<br>" .$m . "<br><br>"; //$t for team and m for marks
echo "<br/>";
}
In this way you can parse your different data in a paralell way
From the looks of what you are doing, you are using two foreach loops with different output...
This one:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
echo "// And its mark<br><br>";
}
Will output this:
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
While this loop:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
}
foreach (array_values($exam) as $i => $value) {
echo "// And its mark<br>";
}
Will output this:
First-Term
Second-Term
Third-Term
// And its mark
// And its mark
// And its mark
Will update this answer once I have more details.
Code tested: https://3v4l.org/RDvYN
I would build an array with everything in place and then start to display it:
$exam = array("First-Term","Second-Term", "Third-Term");
$marks = array(1, 2, 3);
$result = array();
foreach (array_values($exam) as $idx => $value) {
$result[] = array(
"exam" => $value,
"mark" => $marks[$idx]
);
}
foreach ($result as $value) {
echo $value['exam'] . "\n";
echo $value['mark'] . "\n\n";
}
I am trying to generate sql statement dynamically with loops but i am not getting any idea on how to do it with html name array.
assuming $name and $message are post arrays ... and assuming length of both will be equal,
following is a method i tried;
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($values as $key){
foreach ($key as $value){
echo $value.",";
}
}
?>
output is =
name1,name2,message1,message2,
but i want output as =
(name1,message1),(name2,message2),
Edit : I have acess to $values only and I will not be able to determine how many values are going to join in $values ..
like it can be
$values=array($name,$message,$phone);
and the result i want will be
(name1,message1,phone1),(name2,message2,phone2)
My solutions is
Step 1: Loop your $values this will gonna loop every index of your array like $name
foreach($name as $index => $value) {
// do something
}
Step 2: Inside your loop values start with ( which mean wrap your detail in (
echo "(";
Step 3: loop parent array
foreach($values as $key => $arr) {
// do something
}
Step 4: Inside the loop of your parent array display each data according to your index
echo $values[$key][$index];
$key represents the index of your parent array while $index represents the index of your child array like $name
this loop will create data like
(name1,message1,phone1)
and I just add this
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
to avoid adding , after the last loop
This code will dynamically display array you put inside $values
So your code would be like this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$married= array('yes','no','yes','yes' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
echo "(";
foreach($values as $key => $arr) {
echo $values[$key][$index];
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
}
echo "),";
}
Demo
or this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
$join = array();
foreach($values as $key => $arr) {
$join[] = $values[$key][$index];
}
echo "(".implode(",",$join)."),";
}
Demo
$name = array('name1','name2' );
$mess = array('message1','message2' );
foreach ($names as $k => $v){
echo "(".$v.",".$mess[$k]."),";
}
Try this, you not need two foreach loop, only use foreach loop and pass key to other array and get value
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($name as $keys => $vals)
{
echo "(".$vals.",".$mess[$keys]."),";
}
DEMO
You can use arrap_map() function in order to join two array. Here is reference http://php.net/manual/en/function.array-map.php
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$value = array_map(null, $name, $mess);
print_r($value);
?>
I have an array that looks like this:
$array = array(
array(
"http://google.com",
"Google"
),
array(
"http://yahoo.com",
"Yahoo"
)
);
What is the simplest way to loop through it. Something like:
foreach ($array as $arr) {
// help
}
EDIT: How do I target keys, for example, I want to do:
foreach ($array as $arr) {
echo '<a href" $key1 ">';
echo ' $key2 </a>';
}
In order to echo out the bits you have to select their index in each array -
foreach($array as $arr){
echo ''.$arr[1].'';
}
Here is an example.
Use nested foreach() because it is 2D array. Example here
foreach($array as $key=>$val){
// Here $val is also array like ["Hello World 1 A","Hello World 1 B"], and so on
// And $key is index of $array array (ie,. 0, 1, ....)
foreach($val as $k=>$v){
// $v is string. "Hello World 1 A", "Hello World 1 B", ......
// And $k is $val array index (0, 1, ....)
echo $v . '<br />';
}
}
In first foreach() $val is also an array. So a nested foreach() is used. In second foreach() $v is string.
Updated according to your demand
foreach($array as $val){
echo ''.$val[1].'';
}
The easiest way to loop through it is:
foreach ($array as $arr) {
foreach ($arr as $index=>$value) {
echo $value;
}
}
EDIT:
If you know that your array will have always only two indexes then you can try this:
foreach ($array as $arr) {
echo "<a href='$arr[0]'>$arr[1]</a>";
}
First modify your variable like this:
$array = array(
array("url"=>"http://google.com",
"name"=>"Google"
),
array("url"=>"http://yahoo.com",
"name"=>"Yahoo"
));
then you can loop like this:
foreach ($array as $value)
{
echo '<a href='.$value["url"].'>'.$value["name"].'</a>'
}
The way to loop through is,
foreach($array as $arr)
foreach($arr as $string) {
//perform any action using $string
}
Use the first foreach loop without { } for the simplest use.
That can be the most simple method to use a nested array as per your request.
For your edited question.
Wrong declaration of array for using key.
$array = array(
"http://google.com" => "Google",
"http://yahoo.com" => "Yahoo" );
And then, use the following.
foreach ($array as $key => $value)
echo "<a href='{$key}'>{$value}</a>";
This doesn't slow down your server's performance.
In modern versions of php, you can assign (destructure) subarray values to variables of your choosing.
A good tutorial: https://stitcher.io/blog/array-destructuring-with-list-in-php
Code: (Demo)
$array = [
["http://example1.com", "Example 1"],
["http://example2.com", "Example 2"]
];
foreach ($array as [$key1, $key2]) {
echo "$key2\n";
}
Output:
Example 1
Example 2
To be honest, I'd probably name the variables $url and $text respectively.
I have an array called $topProductIdResults and it looks like the following:
Array ( [11497522] => 2 )
The keys are prodcuct ID's and the value is the number of 5 star ratings that the product has recieved.
I want it to echo out this data using a loop. However I can't work our how to echo out both the key and value. Sometimes there will be several product ID's and number pairs in this array. Please let me know where I'm going wrong. My code so far is:
foreach ($topProductIdResults as $prod) {
echo $prod[0];
echo $prod[1];
}
which just echo's 22 at the moment. I want it to echo 11497522 2
foreach ($topProductIdResults as $key => $value) {
echo $key;
echo $value;
}
Try this :
foreach ($topProductIdResults as $key=>$prod) {
echo $key;
echo $prod;
}
Ref: http://php.net/manual/en/control-structures.foreach.php
If you just have a single dimensional array with key and value Array ( [11497522] => 2 ) , then you can use this :
$array = array(11497522=>2);
$key = key($array);
$value = $array[$key];
Use this
foreach ($topProductIdResults as $key => $value)
{
echo $key;
echo $value;
}
Try this
foreach ($topProductIdResults as $prodid => $prod) {
echo $prod[0];
echo $prod[1];
}
How do I get the current index in a foreach loop?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
In your sample code, it would just be $key.
If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:
$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}
Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.
This is the most exhaustive answer so far and gets rid of the need for a $i variable floating around. It is a combo of Kip and Gnarf's answers.
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_keys( $array ) as $index=>$key ) {
// display the current index + key + value
echo $index . ':' . $key . $array[$key];
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}
Hope it helps someone.
foreach($array as $key=>$value) {
// do stuff
}
$key is the index of each $array element
$i = 0;
foreach ($arr as $key => $val) {
if ($i === 0) {
// first index
}
// current index is $i
$i++;
}
The current index is the value of $key. And for the other question, you can also use:
current($arr)
to get the first element of any array, assuming that you aren't using the next(), prev() or other functions to change the internal pointer of the array.
You can get the index value with this
foreach ($arr as $key => $val)
{
$key = (int) $key;
//With the variable $key you can get access to the current array index
//You can use $val[$key] to
}
$key is the index for the current array element, and $val is the value of that array element.
The first element has an index of 0. Therefore, to access it, use $arr[0]
To get the first element of the array, use this
$firstFound = false;
foreach($arr as $key=>$val)
{
if (!$firstFound)
$first = $val;
else
$firstFound = true;
// do whatever you want here
}
// now ($first) has the value of the first element in the array
You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.
<?php
$array = array('test', '1', '2');
$keys = array_keys($array);
var_dump($keys[0]); // int(0)
$array = array('test'=>'something', 'test2'=>'something else');
$keys = array_keys($array);
var_dump(array_search("test2", $keys)); // int(1)
var_dump(array_search("test3", $keys)); // bool(false)
well since this is the first google hit for this problem:
function mb_tell(&$msg) {
if(count($msg) == 0) {
return 0;
}
//prev($msg);
$kv = each($msg);
if(!prev($msg)) {
end($msg);
print_r($kv);
return ($kv[0]+1);
}
print_r($kv);
return ($kv[0]);
}
based on #fabien-snauwaert's answer but simplified if you do not need the original key
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_values( $array ) as $index=>$value ) {
// display the current index + value
echo $index . ':' . $value;
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}