Ivco Ivco - 1 month ago 6
PHP Question

PHP array from text

I have this code

<?php
$numbers = "'10', '20', '30'";
$the_array = array($numbers);
$match = "20";
if (in_array($match, $the_array)) echo "OK";
?>


But it's not working, so how can I define the $numbers or the $the_array in order for this to work? If I echo the $numbers it shows:

'10', '20', '30'


And if I put that like this:

$the_array = array('10', '20', '30');


It works, but it's not working the way it's in the above code.

Thanks in advance.

Answer

You can do it for example with:

explode()

see live demo

$numbers = "'10', '20', '30'";
$the_array = explode("'", $numbers);
$match = "20";

if (in_array($match, $the_array)) echo "OK";

or with:

str_getcsv()

see live demo

$numbers = "'10', '20', '30'";
$the_array = str_getcsv($numbers, "'");;
$match = "20";

if (in_array($match, $the_array)) echo "OK";