How to display two arrays in one foreach loop? - php

am storing two arrays in one column.first one is images stored as image1*image2*...etc and second one is descriptions as description1*description2*...etc. i want to use these two set of arrays in one foreach loop.Please help.

Just reference the key:
foreach ($images as $key => $val) {
echo '<img src="' . $val . '" alt="' . $descriptions[$key] . '" /><br />';
}

You can't use foreach, but you can use for and indexed access like so.
$count = count($images);
for ($i = 0; $i < $count; $i++) {
$image = $images[$i];
$description = $descriptions[$i];
}

You could use array_combine to combine the two arrays and then use a foreach loop.
$images = array('image1', 'image2', ...);
$descriptions = array('description1', 'description2', ...);
foreach (array_combine($images, $descriptions) as $image => $desc) {
echo $image, $desc;
}

It does not seem possible by foreach loop. Instead try using for loop. If you are sure both your arrays are of the same size, then try using following code:
for ($i=0; $i<sizeof(array1); $i++) {
echo $arrray1[$i];
echo $arrray2[$i];
}

Related

PHP How to echo a 3-dim array

After searching for an answer in this forum I found only related questions but under other context that would not apply to my case. Here's my problem:
I have a 3-dim array defined in a function like this:
$m_Array[h][$family][$iterator]
the values for
$family range from 6-10;
$iterator from 0-3 but has duplicates (0,1,2,3,1),
and the $m_Array results in values (25,26,30,31,33).
I am unable to echo the result using those indices to get these results once returned from the function.
NOTE: I was able to echo when I had 2-dim $m_Array[h][$iterator] but could not use it because the last value for the iterator would replace the second in the array.
Since I was able to echo the 2-dim, this is not a question on getting the return from the function or iterate over the indices.
Thanks.
Use print_r($arrayName) to print an array. You cannot echo an Array or Object
as others mentioned, you can use var_dump() or print_r(). If you need to access each item then you're going to need nested loops.
foreach($m_Array as $i => $h)
{
//echo $i, $key for h
foreach($h as $j => $family)
{
//echo $j, key for family
foreach($family as $k => $iterator)
{
echo $iterator;
}
}
}
try this:
$keys = array_keys($h);
for($i = 0; $i < count($h); $i++) {
echo $keys[$i] . "{<br>";
foreach($h[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
echo "}<br>";
}
It prints all values and keys

PhP howto sizeof(JSON:array[])

I have a bug in my code but the solution is buried deep in a JSON return
https://api.instagram.com/v1/users/self/media/liked?access_token=207436640.c57b856.b0a8944d1e0c4e70a6ec581679c656b5
There are array[17] I must loop through
foreach ($arr['data'][0]['likes']['data'] as $liker){
echo '<img src="'.$liker['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
Works fine for one, but
for($i = 0; $i < sizeof($arr['data'][]); $i++){
echo '<img src="'.$arr['likes']['data']['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
has less than desirable results.
Fatal error: Cannot use [] for reading in /var/www/localhost/htdocs/instagram2.php on line 68
or if I remove the [], I get 'undefined 'likes'.
How do I properly loop through a JSON subarray?
You way of approaching the for compared to the foreach is wrong. In the foreach the current item during the iteration is automatically assigned to $liker, however nothing like this occurs in the for. You are only incrementing the value of $i.
/// #shaddy has said, this is the correct way to access the array size
/// it is more optimal to calculate it outside of the loop.
$len = sizeof($arr['data']);
/// with a for loop, you have to use $i to calculate the item
for($i = 0; $i < $len; $i++){
$item = $arr['data'][$i];
/// and then access each of the subitems inside $item
...
}
But you also have other problems. You are seemingly trying to output the image of each of the profile_pictures for the likers; but this is also an array of data. In your first example you are directly stepping through this array, so everything works. In your second however you are only looping the container array, and not the list of likers. To get this to work you must have a second loop:
$len = sizeof($arr['data']);
/// with a for loop, you have to use $i to calculate the item
for($i = 0; $i < $len; $i++){
$item = $arr['data'][$i];
/// best to check for existence before accessing to avoid errors
if ( !empty($item['likes']['data']) ) {
$likers = $item['likes']['data'];
$len2 = sizeof($likers);
/// step each of the likers
for($k = 0; $k < $len2; $k++){
$liker = $likers[$k];
if ( !empty($liker['profile_picture']) ) {
echo '<img src="'.$liker['profile_picture'].'" /></br>';
}
/// the username field is also part of the user array inside item
if ( !empty($liker['username']) ) {
echo '<p> '.$liker['username'].'</p></br>';
}
}
}
}
However the above all looks quite complicated, I usually don't use for loops in php, foreach has a much nicer interface to work with, and is designed to work with arrays:
foreach ( $arr['data'] as $i => $item ) {
if ( !empty($item['likes']['data']) ) {
foreach ( $item['likes']['data'] as $k => $liker ) {
if ( !empty($liker['profile_picture']) ) {
echo '<img src="' . $liker['profile_picture'] . '" /></br>';
}
if ( !empty($liker['username']) ) {
echo '<p> ' . $liker['username'] . '</p></br>';
}
}
}
}
Of course you may just have been wanting to loop through the likers array just like in your first example, to do that with a for you just need:
$likers = $arr['data'][0]['likes']['data'];
$len = sizeof($likers);
for( $i = 0; $i < $len; $i++ ){
echo '<img src="' . $likers[$i]['profile_picture'] . '" /></br>';
echo '<p> ' $likers[$i]['username'] . '</p></br>';
}
please note:
There is also another caveat to be aware of, and this will cause some of the above snippets to fail if it is not true. All the above code is always working with arrays, and so the $arr array must only contain arrays. However your dataset shows a mixture of arrays and objects. When dealing with objects in PHP you need to use a different accessor.
As I am unable to see how you are loading your JSON it is difficult to advise, as depending on the manner objects can be converted into arrays. All your examples have been treating every part of your structure as an array, and that is why I have assumed the same in the above.
However the standard way would be to use json_decode which would/should preserve the array/object difference by default. This means where ever there is an object you will need to use $obj -> prop rather than $obj['prop'], so my preferred example above would look like this:
foreach ( $arr['data'] as $i => $item ) {
if ( !empty($item->likes['data']) ) {
foreach ( $item->likes['data'] as $k => $liker ) {
if ( !empty($liker->profile_picture) ) {
echo '<img src="' . $liker->profile_picture . '" /></br>';
}
if ( !empty($liker->username) ) {
echo '<p> ' . $liker->username . '</p></br>';
}
}
}
}
Also if you prefer working just with arrays, you could use something like this:
https://coderwall.com/p/8mmicq/php-convert-mixed-array-objects-recursively
Well $arr['data'][] is invalid way to reference the data value of the array the correct one is $arr['data']
for($i = 0; $i < sizeof($arr['data']); $i++){
foreach ($arr['data'][$i]['likes']['data'] as $liker) {
echo '<img src="'.$liker['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
}
You can read more about arrays here http://php.net/manual/en/language.types.array.php .

Array To String Conversion error from a double array

I am trying to do a double array to echo out "brown dog" and "white cat". I got an "Array to string conversion" error on the line where I am trying to echo out the statement. How can I fix this error? Thanks in advance. Below is my code:
<?
$pet1 = "dog";
$pet2 = "cat";
$arrayvalue = array();
$arrayvalue[0] = array("brown, "white");
$arrayvalue[1] = array("$pet1", "$pet2");
foreach($arrayvalue as $array)
{
echo "$arrayvalue[0] &nbsp $arrayvalue[1] </br>";
}
?>
The only way I can see this working is with a for loop. If you need to keep the current structure as it is, do this:
for ($i=0; $i<2; $i++)
echo $arrayvalue[0][$i] . ' ' . $arrayvalue[1][$i] . '<br>';
Here is how I would rewrite the program, keeping the current array structure and using the above for loop to solve your problem:
$pet1 = 'dog';
$pet2 = 'cat';
$arrayvalue = array(
array('brown', 'white'),
array($pet1, $pet2)
);
for ($i=0; $i<2; $i++)
echo $arrayvalue[0][$i] . ' ' . $arrayvalue[1][$i] . '<br>';
Output:
brown dog
white cat
You need to edit the foreach loop a little. Also, there's a problem with your quotes above. Try:
<?
$pet1 = "dog";
$pet2 = "cat";
$arrayvalue = array();
$arrayvalue[0] = array("brown", "white");
$arrayvalue[1] = array("$pet1", "$pet2");
foreach( $arrayvalue[0] as $key => $color ) {
echo "$color &nbsp $arrayvalue[1][$key] </br>";
}
?>
Basically instead of iterating through $arrayvalue, you should be going through the one with the colors or the one with the pets. In my example, I go through the one with the colors, and then reference the one with the pets, using $key to keep them in sync.
If possible, I would recommend using two separate arrays instead of one, or naming it more logically:
$array['colors'] = array("brown", "white");
$array['pets'] = array("$pet1", "$pet2");
foreach( $array['colors'] as $key => $color ) {
echo "$color &nbsp $array['pets'][$key] </br>";
}
//or
$colors = array("brown", "white");
$pets = array("$pet1", "$pet2");
foreach( $colors as $key => $color ) {
echo "$color &nbsp $pets[$key] </br>";
}
You are referencing $arrayvalue inside your foreach loop, when you should be using $array
foreach($arrayvalue as $array)
{
echo "{$array[0]} &nbsp {$array[1]} </br>";
}

Arrays and nested foreach

I have two array output (using preg_match_all), for example: $name[1] and $family[1].
i need to put these arrays together, and i use foreach as this:
foreach( $name[1] as $name) {
foreach( $family[1] as $family) {
echo $name.$family.'<br />';
}
}
but it don't work.
(each foreach loop works separately)
Assuming they have matching keys for the loop:
foreach( $name as $key => $value) {
echo $value[$key] . $family[$key] . '<br />';
}
This will go through each match for $name and print it out, and then print out the corresponding $family with it. I don't think you want to hardcode [1].
If you do, I'm a little confused and would like to see a var_dump of both $name and $family for clarification.
$together= array();
foreach( $name as $key => $n) {
$tuple= array('name'=>$name[$key],'family'=>$family[$key]);
$together[$key]= $tuple;
}
foreach( $together as $key => $tuple) {
echo "{$tuple['name']} {$tuple['family']}<br />";
}
Use array_combine():
Creates an array by using the values from the keys array as keys and
the values from the values array as the corresponding values.
PHP CODE:
$nameFamilly=array_combine($name[1] , $family[1]);
foreach( $nameFamilly as $name=>$familly) {
echo $name.$family.'<br />';
}

how do i create post values as a session array?

How do I create post values as a session array passing session to another pages? I'm working on a code it is showing only Array on the other pages when i echo $_SESSSION['size'];?
Here My Both Functions:
$size = array('size');
$_POST['size'];
$_SESSION['size'] = array();
foreach ($size as $key)
{
if (isset($_POST[$key]))
{
$_SESSION['size'][$key] = $_POST[$key];
}
}
$size=$_POST['size'];
$max= count($_POST['size']);
for($i=0; $i<$max; $i++)
{
$_SESSION['size']= $_POST['size'];
}
Both Function Are Showing Only Array On The Other Pages...
When you echo $_SESSION['size'] it will show Array because its an array, not single value.
If you want to check values, use this construction:
foreach($_SESSION['size'] as $key=>$val) {
echo $key . '=>' . $val . '<br />';
}
Instead of
echo $_SESSION['size'];
You can also use:
var_dump($_SESSION['size']);
or
print_r($_SESSION['size']);
On the first page simply store the value(s):
$_SESSION['size'] = $_POST['size'];
Now, if your POST contained only a single value for size, you simply use this:
echo $_POST['size'];
// or this:
some_function($_POST['size']);
However, if your POST really had an array of values for size (which is possible), you would also have an array in your session. You then need a simple loop:
foreach ($_SESSION['size'] as $size) {
echo $size;
// or this:
some_function($size);
}
Combined code that handles both cases:
if (is_array($_SESSION['size'])) {
foreach ($_SESSION['size'] as $size) {
echo $size;
// or this:
some_function($size);
}
} else {
echo $_SESSION['size'];
// or this:
some_function($_SESSION['size']);
}

Categories