Find the key of a corresponding array value - php

I have an array like this. What i want is to get the value of the index for specific values. ie, i want to know the index of the value "UD" etc.
Array
(
[0] => LN
[1] => TYP
[2] => UD
[3] => LAG
[4] => LO
)
how can i do that??

array_search function is meant for that usage
snipet:
$index = array_search('UD', $yourarray);
if($index === false){ die('didn\'t found this value!'); }
var_dump($index);

Use array_search:
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
$key = array_search('UD', $array); // $key = 2;
if ($key === FALSE) {
// not found
}

Your best bet is:
array_keys() returns the keys, numeric and string, from the input array.
If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
print_r(array_keys($array, "UD"));
Array
(
[0] => 2
)
Possible considerations for not using array_search()
array_search() If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.

I suggest array_flip:
$value = "UD";
$new = array_flip($arr);
echo "result: " . $new[$value];

Just a note: some of these array_* functions are substantially more useful in PHP 5.3 with the addition of anonymous functions. You can now do things like:
$values = array_filter($userArray, function($user)
{
// If this returns true, add the current $user object to the resulting array
return strstr($user->name(),"ac");
});
Which will return all elements in our imaginary array of user objects that contain "ac" ("Jack","Jacob") in their name.
This has been possible in the past with create function, or simply by defining a function beforehand, but this syntax make it a lot more accessible.
http://ca2.php.net/manual/en/functions.anonymous.php

$array = Array(0 => LN, 1 => TYP, 2 => UD, 3 => LAG, 4 => LO);
$arrtemp = array_keys($array,'UD');
echo 'Result : '.$arrtemp[0];
I use array_keys to find it.

Related

PHP - unset array where Key is X and Value is Y

I have this type of array,
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
[1] => Array --> I want to remove this value using its index, which is "1"
(
[id] => 2
[fams] => 5
)
)
I want to remove that array [1] entirely, using its index, so the condition is - where the ID is match, for example - [id] => 2
Is that possible, to remove a particular value with that specific condition?
and without looping (or any similar method that need to loop the array)
thanks in advance!
FYI - I did try to search around, but, to be honest, I'm not sure what "keyword" do I need to use.
I did try before, but I found, array_search, array_keys - and it seems those 2 are not.
I'm okay, if we need several steps, as long as it did not use "loop" method.
---update
I forgot to mention, that I'm using old PHP 5.3.
array_filter should work fine with PHP 5.3.
The downside of this approach is that array_filter will (internally) iterate over all your array's entries, even after finding the right one (it's not a "short-circuit" approach). But at least, it's quick to write and shouldn't make much of a difference unless you're dealing with very big arrays.
Note: you should definitely upgrade your PHP version anyway!
$array = array (
0 =>
array (
'id' => 0,
'fams' => 5
),
1 =>
array (
'id' => 2,
'fams' => 5
)
);
$indexToRemove = 2;
$resultArray = array_filter($array, function ($entry) use ($indexToRemove) {
return $entry['id'] !== $indexToRemove;
});
Demo: https://3v4l.org/6DXjl
You can use array_search to find the key of a sub-array that has a matching id value (extracted using array_column), and if found, unset that element:
if (($k = array_search(2, array_column($array, 'id'))) !== false) {
unset($array[$k]);
}
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
)
Demo on 3v4l.org
It should be noted that although there is no explicit loop in this code, array_search and array_column both loop through the array internally.
You can use array_column to make id as index of the sub-array then use unset
$a = array_column($a, null, 'id');//new array id as index
$index = 2;// id to remove
if($a[$index]) unset($a[$index]);
print_r($a);
Working example :- https://3v4l.org/ofMr7

PHP: Ignore key and extract value of an array

I have a function that returns an array where the value is an array like below: I want to ignore the key and extract the value directly. How can I do this without a for loop? The returned function only has one key but the key (2 in this case) can be a variable
Array ( [2] => Array ( [productID] => 1 [offerid]=>1)
Expected result:
Array ( [productID] => 1 [offerid]=>1)
There're at least 3 ways of doing this:
Use current function, but be sure that array pointer is in the beginning of your array:
$array = Array (2 => Array ( 'productID' => 1, 'offerid' => 1));
$cur = current($array);
var_dump($cur, $cur['offerid']);
Next is array_values function, which will give you array of values with numeric keys, starting with 0
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$av = array_values($array);
var_dump($av[0], $av[0]['offerid']);
And third option is use array_shift, this function will return first element of array, but be careful as it reduces the original array:
$array = Array ( 2 => Array ( 'productID' => 1, 'offerid' => 1));
$first = array_shift($array);
var_dump($first, $first['offerid']);
If you want to get the current value of an array, you can use current() assuming the array pointer is in the correct position. If there is only one value, then this should work fine.
http://php.net/manual/en/function.current.php
I think Devon's answer will work for you , but if not your can try
$arr = array_column($arr, $arr[2]);
if you need always the second index of your master array, if you need all index use
array_map(),
something like array_map('array_map', $arr); should work.

PHP arrays: How to get the index where an element is

Here’s the following array:
Array
(
[1] => Array
(
[0] => 10
[1] => 13
)
[2] => Array
(
[0] => 8
[1] => 22
)
[3] => Array
(
[0] => 17
[1] => 14
)
)
Then I have
$chosenNumber = 17
What I need to know is:
First) if 17 is in the array
Second) the key it has (in this case [0])
Third) the index it belongs (in this case [3])
I was going to use the in_array function to solve first step but it seems it only works for strings ..
Thanks a ton!
function arraySearch($array, $searchFor) {
foreach($array as $key => $value) {
foreach($value as $key1 => $value1) {
if($value1 == $searchFor) {
return array("index" => $key, "key" => $key1);
}
}
}
return false;
}
print_r(arraySearch($your_array, 17));
You should look using these :
in_array()
array_search()
You have used array_search function
$qkey=array_search(value,array);
You use array_search:
$index = array_search($chosenNumber, $myArray);
if($index){
$element = $myArray[$index];
}else{
// element not found
}
array_search returns false if the element was not found, the index of the element you were looking for otherwise.
If a value is in the array multiple times, it only returns the key of the first match. If you need all matches you need to use array_keys with the optional search_value parameter specified:
$indexes = array_keys($myArray, $chosenNumber);
This returns a (possibly empty) array of all indexes containing your search value.
array_keys()
Return all the keys or a subset of the keys of an array
array_values()
Return all the values of an array
array_key_exists()
Checks if the given key or index exists in the array
in_array()
Checks if a value exists in an array
You can find more information here http://www.php.net/manual/en/function.array-search.php

How to grab the key from an array when a value matches another value from a string or another array using PHP?

How can I grab a key from an array where a value equals another value for example lets say I have an array and I want to return the key for a value when a match for the value grEen is made. How would I be able to do this using PHP?
Array
(
[147] => ad
[148] => grEen
[149] => TRUE
)
I bet you are looking for array_search:
$id = array_search('grEen', $inputArray);
// $id = 148
$inverse = array();
foreach($array as $key => $value) {
if(false === array_key_exists($key, $inverse)) {
$inverse[$value] = array();
}
$inverse[$value][] = $key;
}
now you can become all keys in a array with the value 'search-value'
$inverse['search-value']
Actually it's quite easy to achieve...
You've got 2 options:
If all you want is to pull the first matching key; the use the array_search() function
If you want all keys that have that value then use the array_keys() function supplying the optional parameter (it allows you to specify a search_value as the second parameter)
Hope this was helpful?
If you only need to get the id of the first instance found, array_search() is what you want as others have pointed out. If you need ALL instances then preg_grep() can help:
$array = array (
147 => 'ad',
148 => 'grEen',
149 => TRUE,
150 => 'grEen'
);
$greens = preg_grep('/^grEen$/', $array);
$keys = array_keys($greens);
print_r($keys);

checking to see if a vaule is in a particular key of an array

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:
$array1= Array(
[0] => 1_31
[1] => 1_65
[2] => 29_885...)
What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.
foreach($array1 as $key => $value){
$id = explode('_',$value);
}
which gives me:
Array ( [0] => 1 [1] => 31 )
Array ( [0] => 1 [1] => 65 )
Array ( [0] => 29 [1] => 885 )
I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.
Any help would be great.
If the part after underscore is unique, make it a key for new array:
$newArray = array();
foreach($array1 as $key => $value){
list($v,$k) = explode('_',$value);
$newArray[$k] = $v;
}
So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.
You can use preg_grep() to grep an array:
$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));
Outputs:
Array
(
[1] => 1_65
)
See http://ideone.com/3Fgr8
I would say you're doing it just about as well as anyone else would.
EDIT
Alternate method:
$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example
I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

Categories