Hi i am working on some operations where i need to get value of array from its key.
I have $attr_color variable with the value red.
So if red is in the array then it needs to be return its value.
Below is my array :
Array
(
[0] => Array
(
[label] =>
[value] =>
)
[1] => Array
(
[label] => red
[value] => 32
)
[2] => Array
(
[label] => green
[value] => 33
)
[3] => Array
(
[label] => pink
[value] => 34
)
[4] => Array
(
[label] => black
[value] => 35
)
[5] => Array
(
[label] => white
[value] => 36
)
)
I have tried below code but it returns blank :
$attr_color = "red";
//$response is my array which i have mention above.
if(in_array($attr_color,array_column($response,"label")))
{
$value = $response['value'];
echo "Value".$value;
exit;
}
Help ? where i made mistake ?
Use array_search, and check for false:
$index = array_search($attr_color, array_column($response,"label"));
if ($index !== false) {
echo $response[$index]['value'];
}
In your case it's enough to use a regular foreach loop:
$attr_color = "red";
$value = "";
foreach ($response as $item) {
if ($item['label'] == $attr_color) {
$value = $item['value'];
break; // avoids redundant iterations
}
}
Try this simple solution, hope this will help you out. Here we are using array_column for getting columns and indexing it with keys and values, Where keys are labels and values as value
Try this code snippet (with sample inputs)
$result=array_column($array, 'value',"label");
$result=array_filter($result);
echo $result["red"];
By using array_column with third parameter and array_search as
$attr_color="red";
$arr = array_filter(array_column($response, "label", 'value'));// pass thired parameter to make its key
if (array_search($attr_color, $arr)) {// use array search here
echo array_search($attr_color, $arr);
}
Try below code : using array match function :
$your_value = array_search($attr_color, array_column($response,"label"));
if ($index !== false) {
echo $response[$your_value]['value'];
}
Try:
$attr_color = "red";
//$response is my array which i have mention above.
$index = array_search($attr_color, array_column($response, 'label'));
if($index!==false){
$value = $response[$index]['value'];
echo "Value:".$value;
exit;
}
Here $index will get the index of the array with label red
Use array_search instead of in_array
$attr_color = "red";
if(($index = array_search($attr_color,array_column($response,"label")))!==FALSE)
{
$value = $response[$index]['value'];
echo "Value".$value;
exit;
}
Related
here is my array:
[0] => Array
(
[messages] => Array
(
[0] => Array
(
[message] => This is for sandwich
)
[1] => Array
(
[message] => This message is for burger
)
)
[price] => Array
(
[amount] => 5
[currency] => USD
)
[1] => Array
(
[messages] => Array
(
[0] => Array
(
[message] => This is a message for a delicious hotdog
)
)
[price] => Array
(
[amount] => 3
[currency] => USD
)
)
i want to search in ALL arrays and I want to search for the word "burger". I want to get the price and amount of "burger" which is 5. If I search for the word "hotdog", it will return the price amount 3. How can i do that? thanks
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;
If $array be your array. I Think It may Work.
<?php
$check = 'hotdog';
foreach($array as $products){
foreach($products['messages'] as $messages){
if (strpos($messages['message'], $check) !== false) {
echo $check.' Found. Price'. $products['price']['amount'] .'</br>' ;
}
}
}
?>
Here we are using array_column, implode and preg_match.
1. array_column for retrieving specific column of an array
2. implode joins a array with a glue to make it string.
3. preg_match here for matching specific word in the given string.
Try this code snippet here
$toSearch="hotdog";
foreach($array as $key => $value)
{
if(preg_match("/\b$toSearch\b/",implode(",",array_column($value["messages"],"message"))))
{
echo $value["price"]["amount"];
}
}
Because you are searching for the first qualifying price only, it is best practice to use a conditional break to short circuit the loops. There is no reason to do more cycles if you have found a qualifying entry.
Instantiate the $amount variable with a null value before the loop to properly distinguish between a successful search and an unsuccessful one.
str_contain() is the modern function to case-sensitively search for a substring (PHP7.4 and higher). If you need case-insensitivity, you will need to use stripos($message['message'], $needle) !== false. If you need to match whole words, you will need to call preg_match("/\b$needle\b/i", $message['message']). If using regex and the $needle is coming from user input, you will need to apply escaping beforehand with $needle = preg_quote($needle, '/');.
Code: (Demo)
$needle = 'burger';
$amount = null;
foreach ($haystack as ['messages' => $messages, 'price' => $price]) {
foreach ($messages as $message) {
if (str_contains($message['message'], $needle)) {
$amount = $price['amount'];
break;
}
}
}
var_export($amount);
// 5
$champions array =
Array (
[0] => Shen
[1] => Graves
[2] => Lux
[3] => Tristana
[4] => Janna
[5] => Lissandra
[6] => RekSai
[7] => Anivia
[8] => Lucian
[9] => Alistar )
This array has always 10 values.
$fbps array =
Array (
[0] => RekSai
[1] => Alistar
[2] => Lucian )
This array has always 1-5 values.
What i want to make
Array (
[0] => 0
[1] => 0
[2] => 0
[3] => 0
[4] => 0
[5] => 0
[6] => 1
[7] => 0
[8] => 1
[9] => 1 )
My english is bad to explain this, i hope arrays are enough to tell. Sorry for bad title and explanation.
Edit: Ill try to explain it more. For example Shen's key is 0 in first array. $fbps array doesnt have a value named "Shen" so in third array 0 => 0. Lucian's key is 8 in first array. fbps have a value named Lucian. So third arrays 8th key has value "1"
$cArr = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Anivia','Lucian');
foreach ($cArr as $key=>$value) {
if(array_search($value, $fbps) !== false) {
$cArr[$key] = 1;
} else {
$cArr[$key] = 0;
}
}
var_dump($cArr);
Or a more compact version:
$cArr = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Anivia','Lucian');
foreach ($cArr as $key=>$value) {
$cArr[$key] = (array_search($value, $fbps) !== false) ? 1 : 0;
}
var_dump($cArr);
EDIT:
added in the !== false conditional as matches found in position 0 of the $fbps array incorrectly evaluated to false because 0 also = false in PHP land...
EDIT 2:
This function has O(N) complexity, meaning it'll grow linearly and in direct proportion to the size of the input data set.
Does the resulting array just have a value of 1 for every element of $fbps that appears in $champions? If so, something like this should do it;
$champions = ['Shen', 'Graves', 'Alister', '...'];
$fbps = ['Shen', 'Alister', '...'];
$result = array_map(function($value) use ($fbps) {
return (int)in_array($value, $fbps);
}, $champions);
I know you've already accepted an answer but here is the most efficient solution:
<?php
// Your arrays
$champions = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Alistar','Lucian');
// New array which will store the difference
$champ_compare = array();
// Flip the array so that it is associative and uses the names as keys
// http://php.net/manual/en/function.array-flip.php
$fbps = array_flip($fbps);
// Loop all champions and use $v as reference
foreach($champions as &$v)
{
// Check for the existent of $v in the associative $fbps array
// This is leaps and bounds faster than using in_array()
// Especially if you are running this many times with an unknown number of array elements
$champ_compare[] = (int)isset($fbps[$v]);
}
unset($v);
// Flip it back if you need to
$fbps = array_flip($fbps);
print_r($champ_compare);
If you just want the most compact code and do not care about performance then you can try this:
<?php
// Your arrays
$champions = array('Shen','Graves','Lux','Tristana','Janna','Lissandra','RekSai','Anivia','Lucian','Alistar');
$fbps = array('RekSai','Alistar','Lucian');
// New array which will store the difference
$champ_compare = array();
// Loop all champions and use $v as reference
foreach($champions as &$v)
{
// Check if the current champion exists in $fbps
$champ_compare[] = (int)in_array($v, $fbps);
}
unset($v);
print_r($champ_compare);
Not as detailed as Garry's answer, but is based on your existing arrays.
$res = array()
foreach($champions as $key => $val) {
$res[$key] = (in_array($val, $fbps)) ? 1 : 0;
}
var_dump($res)
Edit: I've switched the array_key_exists to in_array.
<?php
$champions = array('Shen', 'Graves', 'Lux', 'Tristana', 'Janna', 'Lissandra', 'RekSai', 'Anivia', 'Lucian', 'Alistar');
$fbps = array('RekSai', 'Alistar', 'Lucian');
$res = array();
foreach($champions as $key => $val) {
$res[$key] = (in_array($val, $fbps)) ? 1 : 0;
}
var_dump($res);
This has to be easy but I am struggling with it. If the array below exists (named "$startersnames") and I specifically want to echo the value that has "qb" as the key, how do I do that?
I assumed $startersnames['qb'], but no luck.
$startersnames[0]['qb'] works, but I won't know that it's index 0.
Array
(
[0] => Array
(
[qb] => Tannehill
)
[1] => Array
(
[rb] => Ingram
)
[2] => Array
(
[wr] => Evans
)
[3] => Array
(
[wr] => Hopkins
)
[4] => Array
(
[wr] => Watkins
)
[5] => Array
(
[te] => Graham
)
[6] => Array
(
[pk] => Hauschka
)
[7] => Array
(
[def] => Rams
)
[8] => Array
(
[flex] => Smith
)
)
You can use array_column (from php 5.5) like this:
$qb = array_column($startersnames, 'qb');
echo $qb[0];
Demo: http://3v4l.org/QqRuK
This approach is particularly useful when you need to print all the wr names, which are more than one. You can simply iterate like this:
foreach(array_column($startersnames, 'wr') as $wr) {
echo $wr, "\n";
}
You seem to be expecting an array with text keys and value for each, but the array you have shown is an array of arrays: i.e. each numeric key has a value which is an array - the key/value pair where you are looking for the key 'qb'.
If you want to find a value at $array['qb'] then your array would look more like:
$array = [
'qb' => 'Tannehill',
'rb' => 'etc'
];
now $array['qb'] has a value.
If the array you are inspecting is a list of key/value pairs, then you have to iterate over the array members and examine each (i.e. the foreach loop shown in your first answer).
For your multi-dim array, you can loop through the outer array and test the inner array for your key.
function findKey(&$arr, $key) {
foreach($arr as $innerArr){
if(isset($innerArr[$key])) {
return $innerArr[$key];
}
}
return ""; // Not found
}
echo findKey($startersnames, "qb");
You can try foreach loop
$key = "qb";
foreach($startersnames as $innerArr){
if(isset($innerArr[$key])) {
echo $innerArr[$key];
}
}
$keyNeeded = 'qb';
$indexNeeded = null;
$valueNeeded = null;
foreach($startersnames as $index => $innerArr){
//Compare key
if(key($innerArray) === $keyNeeded){
//Get value
$valueNeeded = $innerArr[key($innerArray)];
//Store index found
$indexNeeded = $index;
//Ok, I'm found, let's go!
break;
}
}
if(!empty($indexNeeded) && !empty($valueNeeded)){
echo 'This is your value: ';
echo $startersnames[$indexNeeded]['qb'];
echo 'Or: ':
echo $valueNeeded;
}
http://php.net/manual/en/function.key.php
Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best
I've created the multidimensional array in the following format
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
When I try to unset an particular array element based on id, after unset i'm getting the array like below.
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
The array element is getting unset, but the next array element doesn't move to the deleted array position.
For unset an array element, I'm using the following code.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
How to solve this issue? Please kindly help me to solve it.
Thanks in advance.
Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);
Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.
http://www.php.net/manual/en/function.array-splice.php
http://php.net/manual/en/function.unset.php
Why do you use $i++ to find an element to unset?
You can unset your element inside foreach loop:
foreach($cartdetails['products'] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);
Why don't you use this???
$id = 9;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}