1

it's been a while since I'm looking for something, I'm blocked for some time to know how to take keys from a value in a php array.

Here is my array where I start my research :

[It] => z
[is] => h
[soon] => y
[the] => c
[new] => w
[year] => e
[2017] => e
[!] => e

Starting with the value « y », I would like to get the words from another table from this same value than the key [soon] (= "y"), until time is reached this same value.

Here is an exemple of the other array :

[Here] => a
[is] => y
[my] => c
[favorite] => u
[team] => y
[.] => o

Here are the words than I would like to get from this sentence put in a array of my example :

is
my
favorite

I tried in many ways, for example with an "in_array" but without success...

Thank you so much to the person which will respond !

2
  • Hello, If I correctly understand ... If you search for c you want the output my favorite team . Same for a => here is my favorite team. (because there is no other iteration of a) Commented Dec 18, 2016 at 13:37
  • How do you want to create that sentence, on what condition rather? It seems pretty unclear on first sight. Commented Dec 18, 2016 at 13:40

1 Answer 1

1

From what I understand, you're somehow finding the 'y' character from first array, and then filtering out the keys from second array whose values start and end with y.

Assuming you already know the search parameter(i.e y), try the following:

$array2 = array(
  'Here' => 'a',
  'is' => 'y',
  'my' => 'c',
  'favorite' => 'u',
  'team' => 'y',
  '.' => 'o'
);

$search = 'y'; // Search parameter
$freq = 0;     // Frequency of 'y' in second array
$result = array();
foreach ($array2 as $k => $arr) {
    if ($arr == 'y') {
        $freq++;         // Increment every time y appears
    }
    /* If only one y appears, store the array keys in $result */
    if ($freq == 1) {
        $result[] = $k;  
    }
    /* If another y appears, break out from the loop such that $result stores all $array2 keys until the second y appears */
    if ($freq == 2) {
        break;           
    }
}

Output:

Array
(
  [0] => is
  [1] => my
  [2] => favorite
)
Sign up to request clarification or add additional context in comments.

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.