PHP Search Array Key and Get Value

php search array key and get value

The key is already the ... ehm ... key

echo $array[20120504];

If you are unsure, if the key exists, test for it

$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;

Minor addition:

$result = @$array[$key] ?: null;

One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

Update: With PHP7 my previous example is possible without the error-silencer

$result = $array[$key] ?? null;

PHP - Get key name of array value

If you have a value and want to find the key, use array_search() like this:

$arr = array ('first' => 'a', 'second' => 'b', );
$key = array_search ('a', $arr);

$key will now contain the key for value 'a' (that is, 'first').

Search array by value in key and get another key's value

You can use a foreach loop and then use strpos or stripos.

foreach ($array as $row) {
foreach ($row['messages'] as $row2) {
if(strpos($row2['message'], 'burger') !== false) {
$stringFound = true;
} else {
$stringFound = false;
}
}
if($stringFound === true) {
$price = $row['price']['amount'];
} else {
$price = '0';
}
}
echo $price;

PHP: Check if array key has value

If you don't know the first key of array - use array_keys, for example, to get all keys of your array.

$ar = array('95' => 'val');
$keys = array_keys($ar);
$first_item = $ar[$keys[0]];
var_dump($first_item); // outputs: string(3) "val"

Another option can be a current function, which will return you current element of an array. Considering that you don't move array pointer, code can be:

$ar = array('95' => 'new_val', '02' => 'val2');
$cur = current($ar);
var_dump($cur); // outputs: string(7) "new_val"

After that you can use standard emptyfunction to check:

if (empty($cur))

or

if (empty($first_item))

Get key from first array on Search Array in Array PHP

  • You can use in_array to search for the specified serial.
  • I renamed some of your variables to make it clearer.
  • Used break to break out of the loop once we know we've found what we're looking for.
  • assuming you define $serial above your foreach

http://sandbox.onlinephpfunctions.com/code/ca34f236ca2d19af8c098120de1707f14bed285a

<?php

$groep = array(
1 => array("111","222"),
2 => array("333","444")
);

$groepje = 0;
$serial= '333';

foreach($groep as $key => $data) {

if (in_array($serial, $data)) {
$groepje = $key;
break;
}
}

// 2
echo $groepje;

Search PHP array for value and get parent key

You can just use array_search and array_column for this:

$power = 'SuperStrength';
$key = array_search($power, array_column($our_array[0]["powers"], 'power'));
echo "$key\n";
$power = 'Invisibility';
$key = array_search($power, array_column($our_array[0]["powers"], 'power'));
echo "$key\n";

Output:

0
1

Note that array_search returns false (which can be equivalent to 0) if it doesn't find a value, so when checking the result you should use !== false to test for success. For example:

$power = 'Flying';
$key = array_search($power, array_column($our_array[0]["powers"], 'power'));
if ($key !== false) echo "$key\n";
else echo "power $power not found!\n";

Output:

power Flying not found!

Demo on 3v4l.org

Check if a key exists and get a corresponding value from an array in PHP

if(isset($things[$key_to_check])){
echo $things[$key_to_check];
}

How to search by key=value in a multidimensional array in PHP

Code:

function search($array, $key, $value)
{
$results = array();

if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}

foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}

return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

Array
(
[0] => Array
(
[id] => 1
[name] => cat 1
)

[1] => Array
(
[id] => 3
[name] => cat 1
)

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

function search($array, $key, $value)
{
$results = array();
search_r($array, $key, $value, $results);
return $results;
}

function search_r($array, $key, $value, &$results)
{
if (!is_array($array)) {
return;
}

if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}

foreach ($array as $subarray) {
search_r($subarray, $key, $value, $results);
}
}

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).

How to get array key by value?

This is because the in following array initialization:

$servicesTypes = array (
"hotel" => "HTL", "HTP", "HT",
"flight" => "FLT",
"m&a" => "APA",
"daily_tour" => "TOU",
"privat_car" => "PRC",
"transfer" => "4ST"
);

You assign string keys to all of the values except HTP and HT. These items are assigned keys by default by PHP, which are 0, 1, and so on.

It seems that you want to assign the same key to multiple elements in PHP. This is not possible, however.


EDIT OP asked in below comments if it is possible to assign an array of values to every key. This is possible, but it will make the search function more complicated.

I.e., an array like this:

$servicesTypes = array (
"hotel" => array("HTL", "HTP", "HT"),
"flight" => "FLT",
"m&a" => "APA",
"daily_tour" => "TOU",
"privat_car" => "PRC",
"transfer" => "4ST"
);

in which the values can either be strings or arrays, can be found using a get_service_function() like this (cleaned up a bit):

function get_service_type ($servicesArray, $type) {
foreach($servicesArray as $key => $service)
if ( is_array($service) ) {
foreach($service as $value)
if($type == $value)
return $key;
} else if ( $service == $type )
return $key;
return false;
}

What the above function does:

  1. Loops through $servicesArray
  2. If the $service is an array:

    • Loop through the $service.
    • If a match is found, return the key.
  3. Else if the $service is a string:

    • If a match is found, return the key.
  4. If no match, return false.


Related Topics



Leave a reply



Submit