[PHP] Check if string is in Array

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
In this small tutorial I am going to teach you how to check if a string is in an array.

In this example, I am going to use names of people, so to define these, we need to make a new array:
PHP:
$names = array( 'Mark', 'Eminem', 'God' );
Okay, so we have defined the names that we want to have available in the $names variable.

Now, we are going to get the name that is set in the URL Bar.
PHP:
$name = strip_tags( $_GET[ 'name' ] );
The code above will _GET the data that is set in the 'name' parameter in the URL Bar, for example:
Code:
[URL]http://www.site.com/array-script.php?[/URL]name=Mark
Now this is the part where we check if the '$name' variable is in the '$names' array.

PHP:
if( in_array( $name, $names ) )
{
    echo $name . ' is in the array!'; //the $name variable has been found in $names
}
else
{
    echo $name . ' is not in the array!'; //the $name variable has NOT been found in $names
}
Now it is time to piece the full code together:

PHP:
<?php
$names = array( 'Mark', 'Eminem', 'God' );
$name = strip_tags( $_GET[ 'name' ] );
if( in_array( $name, $names ) ) //make sure the variable goes before the actual array ($name, $names) instead of ($names, $name)
{
    echo $name . ' is in the array!'; //the $name variable has been found in $names
}
else
{
    echo $name . ' is not in the array!'; //the $name variable has NOT been found in $names
}
?>
This isn't the most detailed tutorial, but atleast it gets to the point.

Anyway, I hope this helped you.
 

Kryptos

prjRev.com
Jul 21, 2010
2,205
1,252
Nice tutorial!
But, I don't think I get the point of doing this. What I do is this:
Code:
$newsID = strip_tags($_GET['newsid']);
if($newsID) { // news.php?id=1337
echo the news title and post that corresponds to the ID
} else {  // news.php
echo the latest news
}

What I mean is, why would you want to check if it is one of this names?

EDIT: Lol, sorry. I actually wrote that code here,not copying and pasting. Thanks for pointing out my mistake.
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
I'm just using names as an example.
You can use arrays for anything, this is just explaining how to use them.

Also, in the code you have, it should be:
PHP:
strip_tags
not
PHP:
strip-tags
;-)
 
Status
Not open for further replies.

Users who are viewing this thread

Top