PHPNewbie PHPNewbie - 1 year ago 76
PHP Question

Access one row in an array PHP

I have this while loop in php:

<?php while($percentSKU = sqlsrv_fetch_array($resultSKU, SQLSRV_FETCH_ASSOC)) : ?>
<p><?php echo $percentSKU['PercentageSales']; ?>%</p>
<?php endwhile; ?>

Which out puts 12 rows, for example:

.00%, .00%, .00%, .00%, 26.22%, .00%, 3.96%, 1.49%, 5.23%, 20.88%, 42.22%, .00%

Is there a way to only print out 1 particular row?

I have tried things like this:

<?php echo $percentSKU['PercentageSales'][4]; ?>

But because the the array returns a sting, I am getting the nth single character not the nth row of data.
So instead of getting '26.22' im am getting '2'

Any ideas?

adi adi
Answer Source

If it is returning a string you can convert it to an array and access it via its index. To convert a string to an array you can use the explode function.

for ex :

$string = '.00%, .00%, .00%, .00%, 26.22%, .00%, 3.96%, 1.49%, 5.23%, 20.88%, 42.22%, .00%';

$result = explode(',' $string);
$finalvalue = $result[0];

Note : The $result[0] will return the first value of the string, you will have to set the index which you require.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download