PHP array printing using a loop - php

If I know the length of an array, how do I print each of its values in a loop?

$array = array("Jonathan","Sampson");
foreach($array as $value) {
print $value;
}
or
$length = count($array);
for ($i = 0; $i < $length; $i++) {
print $array[$i];
}

Use a foreach loop, it loops through all the key=>value pairs:
foreach($array as $key=>$value){
print "$key holds $value\n";
}
Or to answer your question completely:
foreach($array as $value){
print $value."\n";
}

for using both things variables value and kye
foreach($array as $key=>$value){
print "$key holds $value\n";
}
for using variables value only
foreach($array as $value){
print $value."\n";
}
if you want to do something repeatedly until equal the length of array us this
// for loop
for($i = 0; $i < count($array); $i++) {
// do something with $array[$i]
}
Thanks!

Here is example:
$array = array("Jon","Smith");
foreach($array as $value) {
echo $value;
}

foreach($array as $key => $value) echo $key, ' => ', $value;

I also find that using <pre></pre> tags around your var_dump or print_r results in a much more readable dump.

either foreach:
foreach($array as $key => $value) {
// do something with $key and $value
}
or with for:
for($i = 0, $l = count($array); $i < $l; ++$i) {
// do something with $array[$i]
}
obviously you can only access the keys when using a foreach loop.
if you want to print the array (keys and) values just for debugging use var_dump or print_r

while(#$i++<count($a))
echo $a[$i-1];
3v4l.org

Another advanced method is called an ArrayIterator. It’s part of a wider class that exposes many accessible variables and functions. You are more likely to see this as part of PHP classes and heavily object-oriented projects.
$fnames = ["Muhammed", "Ali", "Fatimah", "Hasan", "Hussein"];
$arrObject = new ArrayObject($fnames);
$arrayIterator = $arrObject->getIterator();
while( $arrayIterator->valid() ){
echo $arrayIterator->current() . "<br />";
$arrayIterator->next();
}

If you're debugging something and just want to see what's in there for your the print_f function formats the output nicely.

Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.

Foreach before foreach: :)
reset($array);
while(list($key,$value) = each($array))
{
// we used this back in php3 :)
}

Related

How to traverse associative array in PHP and access both key and data

I want to traverse an associative array in PHP and access both the key and the data in the most efficient way possible. This has got to be a duplicate, but I can't find a "best practice" example anywhere on SO that says "this is the definitive way to do it in PHP."
Example:
$array = ["one"=>"un", "two"=>"deux", "three"=>"trois"];
foreach ($array as $value){
$key = array_search($value, $array);
print_r($key);
print_r($value);
}
This is horrible; it traverses once per iteration when it searches for the key. Is there a better way to access the index of the array?
Edit:
5.28 seconds for 100k iterations on my machine. php -a
$start=microtime(true);for ($i = 0; $i < 100000; $i++){foreach($array as $value){$key = array_search($value, $array);print_r($key);print_r($value);}}$stop=microtime(true);$time = $stop - $start; print_r($time);
5.3 seconds for:
$start=microtime(true);for ($i = 0; $i < 100000; $i++){foreach($array as $key=>$value){print_r($key);print_r($value);}}$stop=microtime(true);$time = $stop - $start; print_r($time);
So no performance boost? The lack of difference is still there for a larger array:
$array = ["one"=>"un", "two"=>"deux", "three"=>"trois", "four"=>"quatre", "five"=>"cinq", "six"=>"six", "seven"=>"sept", "eight"=>"huit", "nine"=>"neuf", "ten"=>"dix"];
$array = ["one"=>"un", "two"=>"deux", "three"=>"trois"];
foreach ($array as $index=>$value){
echo $index . ' : ' . $value . '<br />';
}
It is indeed simple:
foreach ($array as $key => $value){
echo $key;
echo " ";
echo $value;
echo "<br />";
}

Increment a value inside php foreach?

Is it possible to increment a php variable inside a foreach?
I know how to loop by declaring outside.
I'm looking for something like the syntax below
foreach ($some as $somekey=>$someval; $i++)
{
}
No, you will have to use
$i = 0;
foreach ($some as $somekey=>$someval) {
//xyz
$i++;
}
foreach ($some as $somekey=>$someval)
{
$i++;
}
lazy way of doing is:
{
$i=1;
foreach( $rows as $row){
$i+=1;
}
}
,but you have to scope foreach for $i to dont exist after foreach or at last unset it
$i=1;
foreach( $rows as $row){
$i+=1;
}
unset($i);
, but you should use for cycle for that as leopold wrote.
$dataArray = array();
$i = 0;
foreach($_POST as $key => $data) {
if (!empty($data['features'])) {
$dataArray[$i]['feature'] = $data['features'];
$dataArray[$i]['top_id'] = $data['top_id'];
$dataArray[$i]['pro_id'] = $data['pro_id'];
}
$i++;
}
I know it is an old one here, but these are my thoughts to it.
$some = ['foo', 'bar'];
for($i = 0; $i < count($some); $i++){
echo $some[$i];
}
-- Update --
$some = ['foo', 'bar'];
$someCounted = count($some);
for($i = 0; $i < $someCounted; $i++){
echo $some[$i];
}
It would achieve, what you are looking for in first place.
Yet you'd have to increment your index $i.
So it would not save you any typing.
Is there any reason not to use
foreach ($some as $somekey=>$someval)
{
$i++;
}
?
foreach ($some as $somekey=>$someval)
{
$i++;
}
foreach ($some as $somekey=>$someval)
{
$i++;
}
i is just a variable. Even though it's used to iterate over whatever item you're using, it can still be modified like any other.
This will do the trick!
Remember that you'll have to define $i = 0 before the foreach loop if you want to start counting/incrementing from 0.
$i = 0;
foreach ($some as $somekey=>$someval) {
$i++;
}
Unfortunately, this is not possible. I was looking for an elegant way to do this, very similar to this:
for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }
This works for the for functionality in PHP, but then you would have to pull the item, such as $columns[$k], and then you're back to a less than ideal situation.
Reference

php foreach loop

I have two arrays in my code.
Need to perform a foreach loop on both of these arrays at one time. Is it possible to supply two arguments at the same time such as foreach($array1 as $data1 and $array2 as $data2)
or something else?
If they both the same keys, you can do this:
foreach($array1 as $key=>data1){
$data2 = $array2[$key];
}
Assuming both have the same number of elements
If they both are 0-indexed arrays:
foreach ($array_1 as $key => $data_1) {
$data_2 = $array_2[$key];
}
Otherwise:
$keys = array_combine(array_keys($array_1), array_keys($array_2));
foreach ($keys as $key_1 => $key_2) {
$data_1 = $array_1[$key_1];
$data_2 = $array_2[$key_2];
}
Dont use a foreach. use a For, and use the incremented index, eg. $i++ to access both arrays at once.
Are both arrays the same size always?
Then this will work:
$max =sizeof($array);
for($i = 0; $i < $max; $i++)
array[$i].attribute
array2[$i].attribute
If the arrays are different sizes, you may have to tweak your approach. Possibly use a while.
iterative methods:
http://php.net/manual/en/control-structures.while.php
http://php.net/manual/en/control-structures.for.php
http://php.net/manual/en/control-structures.do.while.php
use for or while loop e.g.
$i = 0;
while($i < count($ar1) && $i < count($ar2) ) // $i less than both length !
{
$ar1Item = $ar1[$i];
$ar2Item = $ar2[$i];
$i++;
}
No to my knowledge with foreach, but can be easily done with for:
<?php
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
for ($i=0;$cond1 || $cond2;$i++)
{
if ($cond1)
{
// work with $array1
}
if ($cond2)
{
// work with $array2
}
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
}
?>

Skip a number of iterations during foreach

I would like to skip a number of iterations of a foreach loop.
I have this code;
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
$key = $skip;
}
echo $letter;
}
This code doesn't do the trick. But with it I can sort of explain what I want. I what to actually move the pointer of the next iteration. It thought that by modifying the value of the key to the one i want would be enough. I understand that a possible solution would be this.
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
continue;
}
echo $letter;
}
But that kinda still does the iteration step. I would like to completely jump over the iteration.
Thanks
See: array_slice
$myarray = array("a","b","c","d","e","f","g","h");
foreach(array_slice($myarray, 5) as $key => $letter){
echo $letter;
}
You could just use a for loop instead
EDIT:
for($i = $skip; $skip > 0, $i < count($myarray); $i++) {
// do some stuff
}
That's not really how foreach loops (and iteration in general) work.
You can either do the continue version (which works fine; if it's the first thing in the loop body, it's essentially the same), or you can construct a different array to iterate over that doesn't include the first elements, or you can use a regular for loop.
<?php
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
$index = 0 ;
foreach($myarray as $key => $letter){
if( ($index % $skip) == 0 ){
echo $letter;
}
$index++;
}
?>
$myarray = array("a","b","c","d","e","f","g","h");
foreach (new LimitIterator (new ArrayIterator ($myarray), 5) as $letter)
{
echo $letter;
}
foreach (array_slice($myarray, 5) as $key => $letter) {
[...]
}
You can call $array->next() for $skip times. There are cases when you cannot easily use a regular for loop: for example when iterating a DatePeriod object.

print all arrary values except first value - php

I have an array of numbers. I can print all values using for each command in php. But what I want is, I don't want to print first value (ie, array[0]) and want to print all other values.
foreach($array as $k=>$val){
if($k){echo $val;}
}
for brevity, i did only exactly what was asked. The first index has a value of 0 which is falsy, so the value won't get echoed when tested in the if condition.
$cloneArray = $array;
array_shift($cloneArray); // will remove the first element of array
foreach($cloneArray as $key => $value){
echo $key." = ".$value;
}
this will also work if your array is in format of
array('key1' => 'value1', 'key2'=> 'value2', ...)
There are dozens..thousands of simple ways to do this. I'm going to list six:
$array = array(5, 6, 7, 8, 9);
foreach ($array as $index => $elem) {
if ($index == 0) {
continue;
}
echo $elem;
}
foreach($array as $index => $elem) {
if ($index != 0) {
echo $elem;
}
}
for ($x = 1; $x < count($array); $x++) {
echo $array[$x];
}
$keep = array_shift($array);
foreach ($array as $index => $elem) {
echo $elem;
}
array_unshift($array, $keep);
foreach (array_diff($array, array($array[0])) as $elem) {
echo $elem;
}
function print_not_zero($elem, $index) {
if ($index) {
echo $elem;
}
}
array_walk($array, 'print_not_zero');
I don't want to insult you, but as a developer you should think more critically for a moment and take the time to visualize the problem. Otherwise you might waste too much time on stackoverflow.
$i = 0
foreach($array as $single)
{
if ($i > 0)
echo $single;
$i++;
}
Although, unless you're using an associative array, a for cycle would be better perhaps.
$i=array(0,1,2,3);
foreach($i as $key=>$value)
{
if($key!='0')
echo $value;
}

Categories