0

Ok, so basically I have a query that returns an array, and then it gets looped:

$result = mssql_query("SELECT * FROM Segments ORDER BY Squares");

    if (!$result) {
    echo 'query failed';
    exit;

              }

        while ($row = mssql_fetch_array($result)) {
    $txtsquares = $row["Squares"];
    echo $txtsquares;

When echoed the variable $txtsquares is equal to an array value, for example lets say 1 2 3 4 5 6 7 8.

I need this array/loop. But I would like to grab the first value of this array and use it in an if statement, like so:

value="<?php echo $txtsquares; ?>"
<?php if ($txtsquares == 1) { ?> checked="checked" <?php }
else{ ?> checked="" <?php } ?>/>

However obviously this is wrong, because the value will never equal 1 because its an array. Can anyone point me in the correct direction? I am new at PHP so sorry if it is an easy question, I have Googled it but without much luck.

2
  • Use PDO over mssql_*. At the very least you should probably use sqlsrv_*. Commented Oct 17, 2012 at 15:09
  • 3
    Is txtsquares actually an array, or is it a string with space-separated values? Commented Oct 17, 2012 at 15:11

2 Answers 2

2

If you need to use the first element of $txtsquares try this:

value="<?php echo $txtsquares; ?>"
<?php if ($txtsquares[0] == 1) { ?> checked="checked" <?php }
else{ ?> checked="" <?php } ?>/>
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming $txtsquares is a string of numbers, and you know it's a string of numbers... you could do something like this:

$txtsquares = "1234";

$str_values = str_split($txtsquares);
// array('1', '2', '3', '4')

$int_values = array_map(function($i) { return (int)$i; }, $str_values);
// array(1, 2, 3, 4)

$first_value = $int_values[0];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.