Home php Find a value in a php array

Find a value in a php array

Author

Date

Category

Greetings! There was a problem. There is an array ()
[0] = & gt; 123
[1] = & gt; orange
[2] = & gt; apple
[3] ...

and in it, for example, 50,000 values.
You need to find the Apple value in it and return its key.

Are there functions like in_array that would just return a key?
I tried the array_search function, but as I understood it, it passes through the entire array and takes a lot of time, while in_array, as I understand it, checks and takes much less time. So how do you do that to find Apple and return its key?


Answer 1

“function of type in_array just to return a key” is array_search ()

However, you don’t need to imagine that a built-in function will perform a search in some special magical way, and it will do it faster than a manually written loop. These functions will search in the same way by brute force, which will be very inefficient for an array of such size.

therefore, first of all, you should try to avoid such a search altogether. For example, by writing data to the database, and making search queries to it already.

Or by representing the array in a different form, for example by writing the values ​​as keys to another array. This will work if there are no duplicate values ​​in the array.

In any case, a specific solution depends on the details of a specific problem.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions