-1

Hello here i am with freaky problem,i wants the first data and last data from for-each loop. for that i have seen this answer. this would be really helpful but here my condition is really a little bit complex. I have loop as following

<?php
    $count = 0;
    $length = count($myDataArray);
    foreach ($myDataArray as $value) {
        if($count >= 7)
        {
            //Some Data to Print
            //this is first data for me

            <tr >
                <td><?=$myfinaldate?></td>
                <td><?=$stockdata[1]?></td>
                <td><?=$stockdata[2]?></td>
                <td><?=$stockdata[3]?></td>
                <td <?php if($count == 8)echo "style='background-color:#47ff77;'"; ?>><?=$stockdata[4]?></td>
                <td><?=$stockdata[5]?></td>
                <td><?php echo $mydate; ?></td>
            </tr>
            <?php

        }
        $count++;
    }

Now How can i Get First And Last Data from loop ?

3 Answers3

0

I imagine you could use your length attribute. As you have the total of your array, just check myDataArray[0] and myDataArray[$length-1] ?

TarangP
  • 2,711
  • 5
  • 20
  • 41
Lilian Barraud
  • 337
  • 1
  • 11
0

To fetch first and last value of the array use the below function :

$array = $myDataArray;

$array_values = array_values($myDataArray);

// get the first value in the array
print $array_values[0]; // prints 'first item'

// get the last value in the array
print $array_values[count($array_values) - 1]; // prints 'last item'
prakash tank
  • 1,269
  • 1
  • 9
  • 15
0

You can use array_values to remove the keys of an array and replace them with indices. If you do this, you can access the specified fields directly. Like this you can check for your requirements on the array without looping over it, as shown in the if-conditions below:

$length = count($myDataArray);
$dataArrayValues = array_values($myDataArray);
$wantedFields = [];
if ($length >= 8) {
    $wantedFields[] = $dataArrayValues[7];
    if ($length > 8) {
        $wantedFields[] = end($dataArrayValues);
    }
}

Due to the conditions you will not print the 8th field twice in case it is the last field as well.

foreach ($wantedFields as $value) {
    <tr>
    ... //Your previous code
    </tr>
}
Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25