0

I'm having a trouble. I was trying to make it work for a long time, so I decided to ask for help here.

I have an with some arrays inside it:

$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];

I am making a function that search for a s

function searchArray($array,$chave,$id) {

   foreach ($array as $key) {
           if (is_array($key)) {

            if (($key[0] == $chave) && ($key[1] == $id)) {
              break;
            }  
               else {
               searchArray($key,$chave,$id);
               }
           }
   } 
    return $key;
} 

$result = searchArray($myarray,'string6','string7');
print_r($result);

It was supposed to print ['string6','string7','string99']] But it it printing the last "key" of the array: ['string8','string9']

The break is not working. After the break, it continue checking the next arrays.

2
  • 1
    so why should it print ['string6','string7','string99'] ? You search for string1 and string2 as index 0 and 1. And else you do a senseless recoursion without fetching the return value? I do not understand your logic. what do you want to achieve? i.e. what should be the reason for printing the supposed values? Commented Mar 20, 2015 at 23:47
  • It was wrong. I edited. I'm looking, at really, for string6 and string7. Sorry. Commented Mar 20, 2015 at 23:56

1 Answer 1

1

with these modification it returns the expected values:

<?php

 $myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];

function searchArray($array,$chave,$id) {

    foreach ($array as $key) {
        if (is_array($key)) {
            if (($key[0] == $chave) && ($key[1] == $id)) {
                return $key;
            } else {
                $res = searchArray($key,$chave,$id);
                if($res !== false) {
                    return $res;
                }
            }
        }
    } 
    return false;
} 

$result = searchArray($myarray,'string6','string7');
print_r($result);

the failure was to break on success. That makes no sense.

You need to return the value on success. If no success return false. Imagine it may happen that the searched values will not been found so it should return false.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I have over 5 years of php programming experience, and It really took me a long time.

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.