is it possible display multidemintional array in php using for loop - php

I have a multi-dimensional array like
Array
(
[0] => Array
(
[ename] => willy
[due_date] => 12:04:2011
[flag_code] => 0
)
[1] => Array
(
[Father] => Thomas
[due_date] => 13:04:2011
[flag_code] => 0
)
[2] => Array
(
[charges] => $49.00
)
)
i want to display values of array using php. but still fail. please any one help me to do this task....?

Since you're so adamant that this be accomplished using only for loops, I have to assume this is a homework question. Because of this, I'll point you to several PHP manual pages in the hopes that you'll review them and try to learn something for yourself:
Arrays
For Loops
Foreach Loops
Now, I'm going to break your actual question a few different questions:
Is it possible to display a multidimensional array using for loops?
Yes. It's entirely possible to use a for loop to iterate over a multidimensional array. You simply have to nest for loops inside for loops. i.e. you create a for loop to iterate over the outer array, then inside that loop you use another for loop to iterate over the inner array.
How can I iterate over a multidimensional array using a for loop?
Generally, when you use a for loop, the loop will look something like this:
for($i = 0; $i < $maxValue; $i++) {
// do something with $1
}
While this works well for indexed arrays (i.e. arrays with numeric keys), so long as they have sequential keys (i.e. keys which use each integer in order. for example, an array with keys 0, 1, and 2 is sequential; an array with keys 0, 2, and 3 is not because it jumps over 1), this doesn't work well for associative arrays (i.e arrays with text as keys - for example, $array = array("abc" = 123);) because these arrays won't have keys with the numerical indexes your for loop will produce.
Instead, you need to get a bit creative.
One way that you could do this is to use array_keys to get an indexed array of the keys your other array uses. For example, look at this simple, one-dimensional array:
$dinner = array(
"drink" => "water",
"meat" => "chicken",
"vegetable" => "corn"
);
This array has three elements, each with an associative key. We can get an indexed array of its keys using array_keys:
$keys = array_keys($dinner);
This will return the following:
Array
(
[0] => drink
[1] => meat
[2] => vegetable
)
Now, we can iterate over the keys, and use their values to access the associative keys in the original array:
for($i = 0; $i < count($keys); $i++) {
echo $dinner[$keys[$i]] . "";
}
As we iterate over this loop, the index $i will be set to hold each index of the $keys array. The associated element of this key will be the name of a key in the $dinner array. We then use this key name to access the $dinner array elements in order.
Alternatively, you could use a combination of the reset, current and next functions to iterate over the values in the array, for example:
for($element = current($dinner);
current($dinner) !== false;
$element = next($dinner)
) {
echo $element . "<br />";
}
In this loop, you initialize the $element variable to be the first element in the array using reset, which sets the array pointer to the first element, then returns that element. Next, we check the value of current($dinner) to ensure that there is a value to process. current() returns the value of the element the array pointer is currently set at, or false if there is no element there. Finally, at the end of the loop, we use next to set the array pointer ahead by one. next will return false when we try to read beyond the end of the array, but we ignore that and wait for current to notice that there is no current element to stop the loop.
Now, having written all of that, there really isn't any reason to do jump through all these hoops, since PHP has the built-in foreach construct which allows you to iterate over each of an arrays elements, regardless of key type:
foreach($dinner as $key => $value) {
echo "The element in key '" . $key . "' is '" . $value ."'. <br />";
}
This is why I'm assuming this is a homework assignment, since you would probably never have reason to jump through these hoops in a production environment. It is, however, good to know that such constructs exist. For example, if you could use any loop but a foreach, then it would be a lot simpler to just use a while loop than to try to bash a for loop into doing what you want:
reset($dinner);
while (list($key, $value) = each($dinner)) {
echo "The value of '" . $key . "' is '" . $value . "'.<br />";
}
In summary, to iterate over a multidimensional array with associative keys, you would need to nest loops inside each other as shown in the answer to the first question, using one of the loops shown in the answer to the second question to iterate over the associative key values. I'll leave the actual implementation as an exercise for the reader.

To print the values of a array, you can use the print_r function:
print_r($array);
This saves a for-loop.

Just use the handy function print_r
print_r($myarray);

If you don't want to use the print_r function, then for a true n-dimensional array solution:
function array_out($key, $value, $n) {
// Optional Indentation
for($i=0; $i < $n; $i++)
echo(" ");
if(!is_array($value)) {
echo($key . " => " . $value . "<br/>");
} else {
echo($key . " => <br/>");
foreach($value as $k => $v)
array_out($k, $v, $n+1);
}
}
array_out("MyArray", $myArray, 0);
Not sure if its possible to do with a for loop and mixed associative arrays, but foreach does work just fine.

If you have to do it with a for loop, you want the following:
$count = count($array)
for($i = 0; $i <= $count; $i++)
{
$count2=count($array[$i]);
for($j = 0; $j <= $count2; $j++)
{
print $array[$i][$j] . "<br/>";
}
}

foreach( $array as $row ) {
$values = array_values($row);
foreach( $values as $v ) {
echo "$v<br>";
}
}
Should output:
willy
12:04:2011
0
Thomas
13:04:2011
0
$49.00

This will actually be readable:
echo '<pre>';
print_r($myCoolArray);
echo '</pre>';

You would need to do it using something like assigning array_keys to an array, then using a for loop to go through that, etc...
But this is exactly why we have foreach - it would be quicker to write, read and run. Can you explain why it must be done with for?

Related

how to fetch next value in foreach loop

I have a foreach loop like below code :
foreach($coupons as $k=>$c ){
//...
}
now, I would like to fetch two values in every loop .
for example :
first loop: 0,1
second loop: 2,3
third loop: 4,5
how can I do ?
Split array into chunks of size 2:
$chunks = array_chunk($coupons, 2);
foreach ($chunks as $chunk) {
if (2 == sizeof($chunk)) {
echo $chunk[0] . ',' . $chunk[1];
} else {
// if last chunk contains one element
echo $chunk[0];
}
}
If you want to preserve keys - use third parameter as true:
$chunks = array_chunk($coupons, 2, true);
print_r($chunks);
Why you don't use for loop like this :
$length = count($collection);
for($i = 0; $i < $length ; i+=2)
{
// Do something
}
First, I'm making the assumption you are not using PHP 7.
It is possible to do this however, it is highly, highly discouraged and will likely result in unexpected behavior within the loop. Writing a standard for-loop as suggested by #Rizier123 would be better.
Assuming you really want to do this, here's how:
Within any loop, PHP keeps an internal pointer to the iterable. You can change this pointer.
foreach($coupons as $k=>$c ){
// $k represents the current element
next($coupons); // move the internal array pointer by 1 space
$nextK = current($coupons);
prev($coupons);
}
For more details, look at the docs for the internal array pointer.
Again, as per the docs for foreach (emphasis mine):
Note: In PHP 5, when foreach first starts executing, the internal array pointer is automatically reset to the first element of the
array. This means that you do not need to call reset() before a
foreach loop. As foreach relies on the internal array pointer in PHP
5, changing it within the loop may lead to unexpected behavior. In PHP
7, foreach does not use the internal array pointer.
Let's assume your array is something like $a below:
$a = [
"a"=>1,
"b"=>2,
"c"=>3,
"d"=>4,
"e"=>5,
"f"=>6,
"g"=>7,
"h"=>8,
"i"=>9
];
$b = array_chunk($a,2,true);
foreach ($b as $key=>$value) {
echo implode(',',$value) . '<br>';
}
First we split array into chunks (the parameter true preserves the keys) and then we do a foreach loop. Thanks to the use of implode(), you do not need a conditional statement.
well this'd be 1 way of doing it:
$keys=array_keys($coupons);
for($i=0;$i<count($keys);++$i){
$current=$coupons[$keys[$i]];
$next=(isset($keys[$i+1])?$coupons[$keys[$i+1]]:NULL);
}
now the current value is in $current and the next value is in $next and the current key is in $keys[$i] and the next key is in $keys[$i+1] , and so on.

PHP How to echo certain position of associative array?

My array looks like this:
Array
( [myarr] => Array (
[504] => 2
[508] => 25
)
)
Is it possible to echo a certain position of this array? I have tried:
echo $_SESSION['myarr'][0][0];
I can't seem to get anything to echo back.
EDIT: to be more specific.. Is it possible to echo it based on numeric index?
Use array_keys() to get the keys into an array. Then access the 2D array using indexes in the keys array. Not that this is the best way to do this but it is a way to use numeric indexes to solve your problem.
$keys = array_keys($_SESSION["myarr"]);
$zero = $_SESSION["myarr"][$keys[0]];
It's just a regular nested array. You use the index keys just as you normally would:
echo $_SESSION['myarr'][504]; //2
echo $_SESSION['myarr'][508]; //25
Have a look at Get the first element of an array.
The following should work (untested, so no guaranties):
echo array_shift(array_values($_SESSION))[0][0];
Yes it is possible
print $array['myarr'][508]; // 25
This is getting ugly.
$i = 1;
foreach ($myarr as $array) {
if ($i == 2) echo $array;
$i++;
}

PHP - Getting the index of a element from a array

How can I get the current element number when I'm traversing a array?
I know about count(), but I was hoping there's a built-in function for getting the current field index too, without having to add a extra counter variable.
like this:
foreach($array as $key => value)
if(index($key) == count($array) ....
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
PHP arrays are both integer-indexed and string-indexed. You can even mix them:
array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');
What do you want the index to be for the value 'blue'? Is it 3? But that's actually the index of the value 'yellow', so that would be an ambiguity.
Another solution for you is to coerce the array to an integer-indexed list of values.
foreach (array_values($array) as $i => $value) {
echo "$i: $value\n";
}
Output:
0: red
1: green
2: white
3: blue
4: yellow
foreach() {
$i++;
if(index($key) == $i){}
//
}
function Index($index) {
$Count = count($YOUR_ARRAY);
if ($index <= $Count) {
$Keys = array_keys($YOUR_ARRAY);
$Value = array_values($YOUR_ARRAY);
return $Keys[$index] . ' = ' . $Value[$index];
} else {
return "Out of the ring";
}
}
echo 'Index : ' . Index(0);
Replace the ( $YOUR_ARRAY )
I recently had to figure this out for myself and ended up on a solution inspired by #Zahymaka 's answer, but solving the 2x looping of the array.
What you can do is create an array with all your keys, in the order they exist, and then loop through that.
$keys=array_keys($items);
foreach($keys as $index=>$key){
echo "position: $index".PHP_EOL."item: ".PHP_EOL;
var_dump($items[$key]);
...
}
PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
There is no way to get a position which you really want.
For associative array, to determine last iteration you can use already mentioned counter variable, or determine last item's key first:
end($array);
$last = key($array);
foreach($array as $key => value)
if($key == $last) ....

each() and list() function

I don't understand the each() and the list() function that well. Can anyone please give me a little more detail and explain to me how can it be useful?
Edit:
<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>
Array
(
[1] => bob
[value] => bob
[0] => 0
[key] => 0
)
So does this mean in array[1] there's the value bob, but it's clearly in array[0]?
list is not a function per se, as it is used quite differently.
Say you have an array
$arr = array('Hello', 'World');
With list, you can quickly assign those different array members to variables
list($item1, $item2) = $arr; //$item1 equals 'Hello' and $item2 equals 'World'
The each() function returns the current element key and value, and moves the internal pointer forward.
each()
The list function — Assigns variables as if they were an array
list()
Example usage is for iteration through arrays
while(list($key,$val) = each($array))
{
echo "The Key is:$key \n";
echo "The Value is:$val \n";
}
A very common example for list is when thinking about CSV files. Imagine you have a simple database stored as CSV with the columns id, title and text, such a file could look like this:
1|Foo|Lorem ipsum dolor|
2|Bar|sit amet|
...
Now when you parse this file you could do it like this, using the list function:
$lines = file( 'myFile.csv' );
for ( $i = 0; $i < count( $lines ); $i++ )
{
list( $id, $title, $text, $null ) = explode( '|', $lines[$i], 4 );
echo "Id: $id, Title: $title\n$text\n\n";
}
The other function, each, is basically just an old way to walk through arrays, using internal pointers. A more common way to do that is by using foreach now.
Edit: its probably worth noting that each has been deprecated
Warning: This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged
lets look first at each() : it returns the current value (at first that's $array[0 | "first value in association array ] . so
$prices = ('x'=>100 , 'y'=>200 , 'z'= 300 );
say I wanna loop over these array without using a foreach loop .
while( $e = each($prices) ){
echo $e[key] . " " . $e[value] . "<br/>" ;
}
when each reaches point at a non existing element that would cause
the while loop to terminate .
When you call each(), it gives you an array with four values and the four indices to the array locations.The locations 'key' and 0 contain the key of the current element, and the locations 'value' and 1 contain the
value of the current element.
so this loop would list each key of the array a space and the value then
secondly lets look at list() .
it basically will do the same thing with renaming of 'value' and 'key' although it has to be use in conjunction with each()
while( list($k , $v ) = each($prices) ){
echo $k /*$e[key]*/ . " " . $v /*$e[value]*/ . "<br/>" ;
}
So in a nutshell each() iterates over the array each time returning an array . list() rename the value , key pairs of the array to be used inside the loop .
NOTICE : reset($prices) :
resets each() pointer for that array to be the first element .
http://www.php.net/list
list isn't a function, it is a language construct. It is used to assign multiple values to different variables.
list($a, $b, $c) = array(1, 2, 3);
Now $a is equal to 1, and so on.
http://www.php.net/each
Every array has an internal pointer that points to an element in its array. By default, it points to the beginning.
each returns the current key and value from the specified array, and then advances the pointer to the next value. So, put them together:
list($key, $val) = each($array);
The RHS is returning an array, which is assigned to $key and $val. The internal pointer in `$array' is moved to the next element.
Often you'll see that in a loop:
while(list($key, $val) = each($array)):
It's basically the same thing as:
foreach($array as $key => $val):
To answer the question in your first edit:
Basically, PHP is creating a hybrid array with the key/value pair from the current element in the source array.
So, you can get the key by using $bar[0] and the value by using $bar[1]. OR, you can get the key by using $bar['key'] and the value using $bar['value']. It's always a single key/value pair from the source array, it's just giving you two different avenues of accessing the actual key and actual value.
Say you have a multi-dimensional array:
+---+------+-------+
|ID | Name | Job |
| 1 | Al | Cop |
| 2 | Bob | Cook |
+---+------+-------+
You might do something like:
<?php
while(list($id,$name,$job) = each($array)) {
echo "".$name." is a ".$job;
}
?>
Using them together is, basically, an early way to iterate over associative arrays, especially if you didn't know the names of the array's keys.
Nowadays there's really no reason I know of not to just use foreach instead.
list() can be used separately from each() in order to assign an array's elements to more easily-readable variables.

Interleaving multiple arrays into a single array

I need to merge several arrays into a single array. The best way to describe what I'm looking for is "interleaving" the arrays into a single array.
For example take item one from array #1 and append to the final array. Get item one from array #2 and append to the final array. Get item two from array #1 and append...etc.
The final array would look something like this:
array#1.element#1
array#2.element#1
.
.
.
The "kicker" is that the individual arrays can be of various lengths.
Is there a better data structure to use?
for example,
function array_zip_merge() {
$output = array();
// The loop incrementer takes each array out of the loop as it gets emptied by array_shift().
for ($args = func_get_args(); count($args); $args = array_filter($args)) {
// &$arg allows array_shift() to change the original.
foreach ($args as &$arg) {
$output[] = array_shift($arg);
}
}
return $output;
}
// test
$a = range(1, 10);
$b = range('a', 'f');
$c = range('A', 'B');
echo implode('', array_zip_merge($a, $b, $c)); // prints 1aA2bB3c4d5e6f78910
If the arrays only have numeric keys, here's a simple solution:
$longest = max( count($arr1), count($arr2) );
$final = array();
for ( $i = 0; $i < $longest; $i++ )
{
if ( isset( $arr1[$i] ) )
$final[] = $arr1[$i];
if ( isset( $arr2[$i] ) )
$final[] = $arr2[$i];
}
If you have named keys you can use the array_keys function for each array and loop over the array of keys instead.
If you want more than two arrays (or variable number of arrays) then you might be able to use a nested loop (though I think you'd need to have $arr[0] and $arr[1] as the individual arrays).
I would just use array_merge(), but that obviously depends on what exactly you do.
This would append those arrays to each other, while elements would only be replaced when they have the same non-numerical key. And that might not be a problem for you, or it might be possible to be solved because of attribute order, since the contents of the first arrays' elements will be overwritten by the later ones.
If you have n arrays, you could use a SortedList, and use arrayIndex * n + arrayNumber as a sort index.

Categories