0

I want to save a value to an array. I have a column called numbers values are 1,2,3.

If I select this value, then save it into a variable $value and try to put it into an array:

$array = array($value);

But its not working properly.

6
  • 1
    How are you selecting? Probably use explode. Also using mysql or sql-server? Commented Sep 14, 2017 at 2:13
  • Can you give a var_dump of $value? Commented Sep 14, 2017 at 2:14
  • <?php $array = array("1","2","3"); echo implode(" ",$array); Commented Sep 14, 2017 at 2:17
  • Is this SQL Server or MySQL (you've tagged both, and it's very unlikely that this is correct)? Or does it not matter at all? Your question seems to be about how to handle your data in PHP, not in the database? Commented Sep 14, 2017 at 2:38
  • @GoogleMac string(7) "1,2,3 " Commented Sep 14, 2017 at 3:00

1 Answer 1

1

PHP does not automatically convert strings into integers. Your dump showed that it is one string, so do this:

// separate by the comma into array
$array = explode("," $str); // array( '1', '2', '3' );

// re-create an array, converting strings into integers
foreach ($array as $index => $value) {
    $array[$index] = (int)$value; 
}
Sign up to request clarification or add additional context in comments.

2 Comments

$final_array = array_map('intval',$array); instead of foreach
@JYoThl, Yes, array_map is shorter code, but I was meaning to help the OPer understand what was going on.. 😊 Any who already understand it should use your snippet.

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.