1

Consider an array like this,

$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');

I want to create an array from $sports like this,

$ball = array('Football','cricket ball','tennis ball');

based on the search key(here it is 'ball').

If am looping through the array $sports and checking one by one, will get the result. But then am already inside a loop and that may be even loops more than 50,000 times. So thought of avoiding another loop.

Is there any other way to get this done?

Thanks

2
  • 1
    array_filter() + preg_match() Commented Jan 23, 2014 at 8:38
  • here I don't know which key user will be searching. So how can I define a callback function? Commented Jan 23, 2014 at 8:44

2 Answers 2

3

Try array_filter() + preg_match() functions:

<?php
header('Content-Type: text/plain; charset=utf-8');

$array  = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');

$word   = 'ball';

$results    = array_filter(
    $array,
    function($value) use ($word){
        return preg_match('/' . $word . '/i', $value);
    }
);

print_r($results);
?>

Shows:

Array
(
    [0] => Football
    [1] => cricket ball
    [2] => tennis ball
)
Sign up to request clarification or add additional context in comments.

Comments

2
$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
$input  = 'ball';
$result = array_filter($sports, function ($item) use ($input) {
    if (stripos($item, $input) !== false) {
        return $item;
    }
});
print_r($result);

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.