Click here to Skip to main content
15,891,621 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
$Object = 'Cucumber';


in the cucumber place if i put "C" it should list all the elements from the salad list which are starting from "C". Is their any way to do this?

What I have tried:

<pre>$veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "Onion");
            $fruits  = array("Apple", "Banana", "Orange", "Pineapple", "Grapes", "Watermelon");
            $salad   = array_merge ($veggies, $fruits);
            $Object = 'Cucumber';
            $search = array_keys($salad, $Object);
            print_r($salad) ; 
            print_r($search);
            foreach($search as $value)
                {
                echo $Object;
            } 
Posted
Updated 4-Apr-18 5:35am

1 solution

To match only the beginning of the string in your $salad array, apply the array_filter method.
PHP
$search = array_filter($salad, function($el) use ($Object) {
            return ( strpos($el[0], $Object) !== FALSE );
          });
Here we loop through all elements in the @salad and put them to the test wether or not the first part equals the $Object string.

So your code would be
PHP
$veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "Onion");
$fruits  = array("Apple", "Banana", "Orange", "Pineapple", "Grapes", "Watermelon");
$salad   = array_merge ($veggies, $fruits);
$Object = 'C';

$search = array_filter($salad, function($el) use ($Object) {
        return ( strpos($el[0], $Object) !== FALSE );
    });

print_r($search);
With a result of
Array
(
    [1] => Cucumber
    [2] => Carrot
)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900