Loop through a two-dimensional array - php

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.

Related

How to access associate array of array in php?

I'm from Perl but I'm beginner in PHP. I'm having following array
$rating_data = Array ("51" => Array (5,3,4,2));
I'm trying to access the each data using loop so I tried following
foreach ($keys as $rating_data)
{
foreach ($index as $rating_data[$keys])
{
echo "$index";
}
}
But the above one is not working. I have also tried the below one also,
$all_keys = array_keys($rating_data);
foreach ($keys as $all_keys)
{
foreach ($values as $all_keys)
{
echo "$values";
}
}
But I didn't get the output. It works if I hard code the keys like below:
$rating_data["51"][0];
How to fix this issue.?
You can get the key position and iter value ( sencod level ).
foreach($rating_data as $key => $values)
{
echo $key; // Output "51"
foreach($values as $value)
{
echo $value; // Output: iter1: "5", iter2: "3", iter3: "4", iter1: "2",
}
}
It should be as simple as below:
foreach($rating_data as $key => $values) {
echo $key;
foreach($values as $value) {
echo $value;
}
}
You seem to have your parameters the wrong way around in your foreach statements. I would advise a quick read through the foreach docs.

PHP Print R Foreach Array, getting a string to post as array

Driving me crazy but here goes:
$cat=2,3,4
$test = print_r(explode(',', $cat), true);
echo ''.$test.'';
foreach ($test as $key => $val) {
echo "$key => $val <br>";
}
What I'm hoping to get:
2
3
4
I'm trying to use a string of numbers obtained from another code to build an array, and then show each value on separate lines. What am I doing wrong?
You shouldn't assign print_r() to $test variable... It's a debugging function for printing purposes..
You should write your code like this..
$cat='2,3,4';
foreach(explode(',',$cat) as $v)
{
echo $v."<br>";
}
This should be either:
$test = explode(',', $cat);
or:
print_r(explode(',', $cat), true);
<?php
$cat='2,3,4';
$array = explode(',', $cat);
$test = print_r($array, true);
echo ''.$test.'';
foreach ($array as $key => $val) {
echo "$key => $val <br>";
}
$test is string. You need array for foreach statement.
Try with this:
<?php
$cat = "2,3,4"; // This is a string separated with commas.
$test = explode(',', $cat); // This assign every number to an array item. The print_r() function is not necesary here.
foreach ($test as $value) {
echo $value. "<br />\n";
}
?>
THIS WILL PRODUCE:
2
3
4
Explanation about your errors:
$cat= '2,3,4'; <- ** Missing quotes **
$test = print_r(explode(',', $cat), true); <- **print_r is not needed here **
echo ''.$test.'';
foreach ($test as $key => $val) { <- Not using it propperly
echo "$key => $val ";
}
You miss ; in $cat variable declaration. Use the following code.
$cat=2,3,4;
$test = explode(',', $cat);
foreach ($test as $key => $val) {
echo $val."<br>";
}

How to echo out the values of this array?

How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.

Basic implode foreach

I have the following code of which I want to echo array elements separated by commas. The code outputs the disered list, but without commas. What am I missing?
<?php
$array = get_field('casts');
$elements = $array;
foreach($array as $key => $value) {
echo implode(', ', $value)};
?>
EDIT 1: where $elements are nested arrays.
EDIT 2: Working snippet:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Why are you assigning $elements = $array; and then never using $elements?
Also you don't need to loop (foreach) to implode an array.
Try this:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
// this array_push() function adds $value to the end of $new_array.
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Here is the documentation on implode()
You can play around and test the above code here.
Also next time, add the tag php, otherwise our codes won't get color syntax.

Traverse $_POST Array to show field Names

Is there a way to traverse an array such as $_POST to see the field names and not just the values. To see the values I do something like this.
foreach ($_POST as $value){
echo $value;
}
This will show me the values - but I would like to also display the names in that array. If my $_POST value was something like $_POST['something'] and it stored 55; I want to output "something".
I have a few select fields that I need this for.
You mean like this?
foreach ( $_POST as $key => $value )
{
echo "$key : $value <br>";
}
you can also use array_keys if you just want an array of the keys to iterate over.
You can also use array_walk if you want to use a callback to iterate:
function test_walk( &$value, $key )
{
...do stuff...
}
array_walk( $arr, 'test_walk' );
foreach ($_POST as $key => $value) {
echo $key; // Field name
}
Or use array_keys to fetch all the keys from an array.
foreach ($_POST as $key => $value){
echo $key.': '.$value.'<br />';
}
If you just want the keys:
foreach (array_keys($_POST) as $key)
{
echo $key;
}
Or...
foreach ($_POST as $key => $value)
{
echo $key;
}
If you want both keys and values:
foreach ($_POST as $key => $value)
{
echo $key, ': ', $value;
}
For just the keys:
$array = array_keys($_POST);
Output them with:
var_dump($array);
-or-
print_r($array);

Categories