Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Darrell Conklin
Darrell Conklin
22,377 Points

Find part of a string inside of a variable.

I'm trying to find a function that will check / search for a value inside of a string inside of a variable. Similar to in_array().

Darrell Conklin
Darrell Conklin
22,377 Points

If it even exists and if not then how would I go about doing something like that.

1 Answer

Do you mean like strpos()?

It returns the index of a searched string, or false if the searched string isn't found.

Say I wanted to find 'York' inside of 'New York'

<?php
$string = 'New York';
$find = 'York';

strpos($string, $find); // Would return 4

echo strpos($string, $find) ? 'Found it!' : 'Did not find it.'; // Would echo 'Found it!'

strpos

Is this what you mean?

Darrell Conklin
Darrell Conklin
22,377 Points

Yes that is what I was wanting to do.

Darrell Conklin
Darrell Conklin
22,377 Points

I ended up doing something like this:

<?php

$find = "Full DOB available and matched input";
$test = strpos($response, $find);

if ($test) {
    echo "You have passed age verification.";
} else {
    echo "You have failed age verification";
}

?>

I don't really understand what is going on here:

<?php

echo strpos($string, $find) ? 'Found it!' : 'Did not find it.'; // Would echo 'Found it!'

?>

I'm assuming that is some shorthand syntax for testing if the expression is true?