print all arrary values except first value - php - 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;
}

Related

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

php multidimensional array foreach

I am using three different arrays of the same length, they are filled with values during a foreach loop:
foreach(......)
{
$array1[]=value1;
$array2[]=value2;
$array3[]=value3;
}
Then these arrays must be echoed:
$i = 0;
while($i < count($array1))
{
echo $array1[i];
echo $array2[i];
echo $array3[i];
$i++;
}
Is there a more elegant way to this this, for example a foreach loop an a multidimensional array?
Assuming your arrays :
$a1 = [2,3,4];
$a2 = [6,7,8];
$a3 = [9,10,11];
array_walk($a1, function($v, $k) use($a2, $a3)
{
echo $v;
echo $a2[$k];
echo $a3[$k];
});
Or simply
foreach($a1 as $k => $v)
{
echo $v;
echo $a2[$k];
echo $a3[$k];
}
Note:
You should never placing a count in while condition,
because it will called for each iterations ! that is not optimized
while($i < count($array1))
should be replaced by
$count = count($array1);
while($i < $count)
You could make an object of it? Probably create an actual class but StdClass works.
foreach(...)
{
$obj = new StdClass();
$obj->value1 = $value1;
$obj->value2 = $value2;
$obj->value3 = $value3;
$array[] = $obj;
}
foreach($array as $obj)
{
echo $obj->value1;
echo $obj->value2;
echo $obj->value3;
}
Still not very elegant but no ugly while loop.

Continuously looping through an array

I'm trying to work out how to continuously loop through an array, but apparently using foreach doesn't work as it works on a copy of the array or something along those lines.
I tried:
$amount = count($stuff);
$last_key = $amount - 1;
foreach ($stuff as $key => $val) {
// Do stuff
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
reset($stuff);
}
}
But obviously that didn't work. What are my choices here?
An easy way is to combine an ArrayIterator with an InfiniteIterator.
$infinite = new InfiniteIterator(new ArrayIterator($array));
foreach ($infinite as $key => $val) {
// ...
}
You can accomplish this with a while loop:
while (list($key, $value) = each($stuff)) {
// code
if ($key == $last_key) {
reset($stuff);
}
}
This loop will never stop:
while(true) {
// do something
}
If necessary, you can break your loop like this:
while(true) {
// do something
if($arbitraryBreakCondition === true) {
break;
}
}
Here's one using reset() and next():
$total_count = 12;
$items = array(1, 2, 3, 4);
$value = reset($items);
echo $value;
for ($j = 1; $j < $total_count; $j++) {
$value = ($next = next($items)) ? $next : reset($items);
echo ", $value";
};
Output:
1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4
I was rather surprised to find no such native function. This is a building block for a Cartesian product.
You could use a for loop and just set a condition that's always going to be true - for example:
$amount = count($stuff);
$last_key = $amount - 1;
for($key=0;1;$key++)
{
// Do stuff
echo $stuff[$key];
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
$key= -1;
}
}
Obviously, as other's have pointed out - make sure you've got something to stop the looping before you run that!
Using a function and return false in a while loop:
function stuff($stuff){
$amount = count($stuff);
$last_key = $amount - 1;
foreach ($stuff as $key => $val) {
// Do stuff
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
return false;
}
}
}
while(stuff($stuff)===FALSE){
//say hello
}

PHP: how to iterate through an array, and resume where you left off?

Here's my array:
$array = array(1,2,3,4,5,6,7,8,9,10);
I want to iterate through the array 5 times, do something else, then resume iteration where I left off.
foreach ($array as $value) {
//do something until key 5
}
//do something else now
//resume...
foreach ($array as $value) {
//key should start at 6
}
How can I do this? Is there a way to achieve this with a foreach loop?
Update: I realized it would be silly to repeat the same code twice. The reason I was asking this is because I'm using a foreach loop to display table rows. I wanted to display the first five and hide the rest. So this is what I ended up with:
<?php
$counter = 1;
foreach ($array as $object): ?>
<?php if ($counter > 5): ?>
<tr style="display: none;">
<?php else: ?>
<tr>
<?php endif; ?>
<td><?php echo $object->name; ?></td>
</tr>
<?php $counter++; ?>
<?php endforeach; ?>
You need to use PHP's internal array pointer.
Something like:
$arr = range(0, 9);
for($i = 0; $i < 5; $i++) {
print current($arr);
next($arr);
}
//the pointer should be half way though the array here
something like this:
$counter = 0;
foreach ($array as $value)
{
if($counter == 5)
{
do something random;
$counter++;
continue;
}
//do something until key 5
$counter++;
}
Just curious, but wouldn't calling a function in the array to do what you need done achieve the same result?
Use two arrays:
$first_five = array_slice($array, 0, 5);
$remainder = array_slice($array, 5);
Is there a reason you need to do this with foreach, as opposed to just for?
you can use each() to resume iterating.
$a = array(1,2,3,4);
foreach ($a as $v) {
if ($v == 2) break;
}
while (list($k, $v) = each($a)) {
echo "$k = $v\n";
}
I think jspcal had the best answer so far. The only modification I made to his code was to use a do-while loop instead, so it would not skip the element where first loop breaks.
$arr = array(1,2,3,4);
// Prints 1 2
foreach($arr as $v)
{
if ($v == 3)
{
break;
}
echo "$v ";
}
// Prints 3 4
do
{
echo "$v ";
}
while( list($k, $v) = each($arr) );
(For the problem as stated I wouldn't recommend it but:) You can also use the NoRewindIterator.
$array = array(1,2,3,4,5,6,7,8,9,10);
$it = new NoRewindIterator(new ArrayIterator($array));
foreach($it as $x) {
echo $x;
if ($x > 4) {
break;
}
}
// $it->next();
echo 'taadaa';
foreach($it as $x) {
echo $x;
}
prints 12345taadaa5678910.
(Note the duplication of the element 5. Uncomment the $it->next() line to avoid that).
It's a little kloodgy, but it should work:
foreach($array as $key => $value)
{
$lastkey = $key;
// do things
if($key == 5) break;
}
// do other things
foreach($array as $key => $value)
{
if($key <= $lastkey) continue;
// do yet more things
}

PHP array printing using a loop

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 :)
}

Categories