How to display two elements of array at same time using foreach loop in php?


#1

This is my for each loop,

            <?php 
              $i = 0;
                   foreach($expression as $key => $item) { ?>
                       <span class="slide-item">      
                         <?php 
                       echo $expression[$i].$expression[$i+1];
                        ++$i;
               } ?>'
                        </span>

using this loop code I want to dislay elements or items of expression like this , suppose 1 + 2*3 is the expression then by this loop I should get output like first it will display 1 then +2 should be display to user then * 3 should be displayed
but I am getting output like this
firstly its displaying
1+
+2
2 *
*3
so what should I do to display it like
1
+2
*3
and so on as per the expression

How should I fix it ?


#2

Use the modulo-operator to trigger only odd keys and show the prvious one, with a check on isset().


#3

See also array_chunk().

Although I’d rather create an iterable expression parser …


#4

Tell us what the real problem is instead of asking about your attempted solution to the real problem. You are creating two variables that you don’t even use at all.


#5

@benanamen basically I have stored expression in $expression which is generating randomly and I am displaying each item of that expression one by one in the manner that after displaying first item when next button is clicked then the next item should appear and visisble to user and current item should go to previous position which will not be visible to user, upto this its all working fine for me .


#6

@benanamen Now the real Problem I am facing is that I am displaying only one item at a time i.e firstly its shows operand then on clicking next button its showing operator and so on. but I want to display it like this , if example 1 + 2 = 3 is expression then firstly 1 should appear then +2 should be appear and so on in same manner ,
Thats where I am confused. I 've used above logic but its not showing items like I have explained above , How can I do it?


#7

It would help and eliminate guesswork if the contents of $expression[] were known…

<?php 
echo '<pre>';
  print_r( $expression )  // prettify by adding linefeeds;
echo '</pre>';

#8

hey thanks for help , I tried but its no showing any result now , btw I dont understands this “if the contents of $expression[] were known…”
probably thats why it is not working can you tell me ?


#9

The $expression should be an array. Check using PHP gettype():

echo gettype( $expression );

The PHP function print_r(…) should show the contents of the array $keys and $items.

PHP function var_dump(…) is also very useful.


#10

I checked it and its getting correct expressions and also its showing correct answer too. but how to show them as I explained in comment 6 ?


#11

Please show the contents of the array $expression


#12

when I checked the inspect it showing like this

       <span class="slide-item visible">
                Array
(
    [0] => 2
    [1] => +
    [2] => 2
)

         </span>

the above is just a basic expression which is generated randomly


#13

Try this:

<?php 
  // $i = 0;
  $iCnt = count( $expression );
  foreach($expression as $key => $item) { ?>
      <span class="slide-item">      
        <?php 
            // Prevent item $key not found
           if($key < $iCnt -1)
           {
             echo $item . $expression[$key+1];
             // ++$i;
           } 
     ?>
</span>

Please note this has not been tried because I am currently running on a thumbdrive and installing a new Operating System.


#14

now the expression is 8 +1 =9
I triedyou and its working but its showing the expression like this
8+

then

+1

but for my purpose I want it to disply like
8

then +1
, I also eddited your logic after I tried but its showing same output.


#15

Why didn’t you try this? Works as expected if you have a slight change on the condition, and you can use the coalesce-operator to catch the undefined index. Output:

1
+2
*3

#16

Try this:

<?php 
declare(strict_types=1);
error_reporting(-1);
ini_set('display_errors', 'true');

$expression = [
'8',
'+',
'1',
'3',
'*',
'2',
];

echo '<pre>';
	print_r($expression);
echo '</pre>';	
echo '<hr>';

echo '<span class="slide-item">';      
	$sTotal = '';
	foreach($expression as $key => $item) 
	{ 
	$numeric = (integer) $item;
	if( ($numeric >=1) && ($numeric <=9)  ):
	  echo '<br>numeric ==> ' .$item;
	  $sTotal .= $numeric;
	else:
	  echo '<br>operator ==> ' .$item;
  	  $sTotal .= '&nbsp;' .$item .'&nbsp;';
	endif;  
	} 
echo '<span>';
echo '<br><br>sTotal ==> ' .$sTotal;

Output:

I’m off out for a late lunch…


#17

Having a little fun with arrays:

$expression = ['8','+','3','*','2'];
// fix the "missing" operator for the first number
array_unshift($expression, ' ');
// group number and operator together
$chunked = array_chunk($expression, 2);
// put it all together
echo array_reduce($chunked, function ($string, array $row) {
    return $string . implode(' ', $row) . PHP_EOL;
}, '');

#19

how can I provide you my source code?


#20

I dont think you understood what I was asking. You are still describing HOW you are attempting solving the task at hand.

I am guessing based on the class name slide-item what is really going on is that you have a slideshow of images that should cycle when you click a button. If so, that is what I was asking for.


#21

yes, there is a slideshow but not of images, its of items in an expression i.e operands and operators are sliding one by one when click on button and in addition to this I have created a timer for this , its working fine
But I want it to display in the manner that first element that appear in slide should be opeand then after sliding the next two elements should appear on screen i.e operator and operand both together , its like a math quiz