1

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.

4
  • 1
    You need to learn the basics of arrays: php.net/manual/en/language.types.array.php the first code is not how you create an array, or at least now how you think it does. Commented Oct 19, 2016 at 23:11
  • you seem to know the first method of array creation is wrong, and the 2nd is right. so just use the 2nd? Commented Oct 19, 2016 at 23:16
  • I need those defined like that $numbers = "'10', '20', '30'"; and call those as $the_array = array($numbers); so that's why I'm asking how to modify the code in order to work :) Commented Oct 19, 2016 at 23:17
  • theres probably some function that converts strings to arrays Commented Oct 19, 2016 at 23:19

2 Answers 2

2

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";
Sign up to request clarification or add additional context in comments.

Comments

0

When you are initializing $numbers, you are not initializing it an array with three values, but rather as a string. For example, if you initialized it like this:

$numbers = "There are '12' inches in a foot";

And you echo it, you will get:

There are '12' inches in a foot

That is because a string is echoed. This is what you did. Instead, initialize $numbers as an array. If you want the elements of the array to be numbers, do this:

$numbers = array(10, 20, 30); 

If you want them to be strings, do this:

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

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.