I want to get the name value from the above array for given user value, but without using loops, if it is possible -I know how to do it with loops-. In other words, return the value of name for the given value of user.
Ex: I will give 2 as the user value, and I want to get Name 2. Or, I will give 3 as user value, and I want to get Name 3.
Is this possible without using loops? Maybe with array functions or something.
array_filter expects the array and a function to determine which items are valid. So you could filter the array on all names that have a specific user, just return if the user matches your requirement and you get the item back. You may use currying to have a generalized version of this.
Possibly it is easier to take array_column on both values and array_combine them, so you can just use the user as an index for an array, if the user is unique.
Thank you, that gave me an idea to modify how I get the array from the DB, so that I can use user as index, as you suggested. Though what I did is not the exact answer to my question above, I believe it is more efficient in this case, and it does the job. If I ever need to use this where there is no DB, then I will go back to your suggestion of using array_column to create a new array with assigned keys (or array_filter, which I still couldn’t figure out how to do).
So, instead of getting the array with 0.1.2.3… key values that are assigned automatically like this:
while ($w = $r->fetch_assoc()) $array[] = $w;
I changed it to use user column as key values:
while ($w = $r->fetch_assoc()) $array[$w['user']] = $w;
So that, I can now use user value as index where I need the name values, simply:
$user = 2;
$array[$user]['name'];
// Returns: Name 2