Check If In_Array (in Recursive Associative Array) - php

I have an array similar to this:
array(2) {
[0]=>
array(2) {
["code"]=>
string(2) "en"
["name"]=>
string(7) "English"
}
[1]=>
array(2) {
["code"]=>
string(2) "bg"
["name"]=>
string(9) "Bulgarian"
}
}
How do I check if the string Bulgarian is part of the above array, or alternatively if the lang code 'en' is part of the array? It would be great if I didn't have to use foreach to loop through the entire array and compare the string with each element['code'] or element['name'].

// $type could be code or name
function check_in_array($arr, $value, $type = "code") {
return count(array_filter($arr, function($var) use ($type, $value) {
return $var[$type] === $value;
})) !== 0;
}

I know my code used foreach but it is easy to understand and use.
$language=array();
$language[0]['code']='en';
$language[0]['name']='English';
$language[1]['code']='bg';
$language[1]['name']='Bulgaria';
var_dump(my_in_array('Bulgaria', $language));
function my_in_array($search, $array) {
$in_keys = array();
foreach($array as $key => $value){
if(in_array($search, $value)){
$in_keys[]=$key;
}
}
if(count($in_keys) > 0){
return $in_keys;
}else{
return false;
}
}

You can use this function for recursive search
function in_arrayr($needle, $haystack) {
foreach ($haystack as $v) {
if ($needle == $v) return true;
elseif (is_array($v)) return in_array($needle, $v);
}
return false;
}
Or you can use json_encode on your array and search occurence of substring :)

I had a similar problem, so I made this function, it's like in_array, but it can search in array in the array recursively. I think it's correct but I didn't test in a lot of case. (sorry for my english I'm french)
function in_arrayr($needle, $haystack) {
if(is_array($haystack)){
foreach($haystack as $elem){
$a = in_arrayr($needle,$elem)||$a;
}
}
else{
$a = (($needle == $haystack)? true: false);
}
return $a;
}

Related

Retrieve indexes of value in array

Is it possible to search an array for a given value and return all the indexes at which the value was found? So for this array:
["Red","Green","Red","Blue"]
I need
[0,2]
with regard to a search for "Red". Searching for "Yellow" in this case would return an empty array.
You can use like this:
$array = ["Red","Green","Red","Blue"];
$output = array_keys($array, "Red");
The $output will be [0,2]
I think this should work:
$input = ["Red","Green","Red","Blue"];
$x = "Red";
$keys = array_keys(array_filter($input, function ($v) use ($x) { return $v === $x;}));
You can iterate the array with foreach:
foreach($input_arr as $key => $value){
if($value == 'Red'){
needed_key_arr[] = $key;
}
}
Also, if you can have an array of values you what to search use:
$lookup_arr = ['Red', 'Green'];
foreach($input_arr as $key => $value){
if(in_array($value, $lookup_arr)){
needed_key_arr[] = $key;
}
}
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) { // filter the first array
return array_filter($valueToSearchFor, function ($val) use ($val1) { // use the first array's value
return $val == $val1; // compare them and then return them
});
}));
var_dump($keys) // array(2) { [0]=> int(0) [1]=> int(2) }
First we filter the array then take the values from the first filter to another filter then we match the arrays and we return them. This works for multiple values too.
$arr = ["Red","Green","Red","Blue"];
$valueToSearchFor = ["Red", "Blue"];
$keys = array_keys(array_filter($arr, function ($val1) use ($valueToSearchFor) {
return array_filter($valueToSearchFor, function ($val) use ($val1) {
return $val == $val1;
});
}));
var_dump($keys) // array(3) { [0]=> int(0) [1]=> int(2) [2]=> int(3) }

how to take array with specific char?

i have array
Example :
array(3) { [0]=> string(6) "{what}" [1]=> string(5) "[why]" [2]=> string(5) "(how)" }
and then how to take array with specific char ("{") ?
Is my understanding here correct? You want to get items in array that has a "{" Character. Then why not just loop over it and check the item if it has that character and push it in a new array.
$array_with_sp_char = array();
foreach ($arr_items as $item) {
if (strpos($item, '{') !== FALSE) {
array_push($array_with_sp_char, $item);
}
}
Just iterate through your array and filter out the values you are interested in, in your case i guess it's the values that contain the Char "{"
A possible implementation:
$result = array_filter($your_array, function($value) {
return preg_match('/{/', $value);
});
Use a combination of array_filter and strpos:
$array = [
"{what}",
"[why]",
"(how)"
];
$array = array_filter($array, function($value) {
return strpos($value, '{') !== false;
});
print_r($array);
That will give you:
Array
(
[0] => {what}
)

PHP: Detecting references in $GLOBALS

I have a simple way to detect references in an array (For debugging purposes)
First I clone the array with array_values and then I alter the clone and look for changes in the original. If it's changed that element is a reference.
Short example:
<?php
$a = [
'a' => 'b',
2 => 3,
];
$b = ['wow'];
$a['ref'] = &$b;
function getrefs($array) {
$marker = uniqid();
$copy = array_values($array);
$i = 0;
$return = [];
foreach ($array as $key => &$val) {
$stash = $val;
$copy[$i] = $marker;
if ($val === $marker) {
$val = $stash;
$return[] = $key;
}
$i++;
}
return $return;
}
var_dump($a);
var_dump(getrefs($a));
The problem is that when I try to use this on $GLOBALS it's not working, and I can't figure out why. Everything in $GLOBALS should be a reference by all rights.
Is $GLOBALS just so strange that it's the only array where array_values won't correctly copy references?
It's a possibility that you're not accounting for recursion. The built-in PHP function:
var_dump($GLOBALS);
Will have the following output
array(7) {
["_GET"]=>
array(0) {
}
["_POST"]=>
array(0) {
}
["_COOKIE"]=>
array(1) {
["PHPSESSID"]=>
string(26) "od602et6qcfj6pa3pkjtl8go57"
}
["_FILES"]=>
array(0) {
}
["GLOBALS"]=>
*RECURSION*
["_SESSION"]=>
&array(0) {
}
}

php loop through array

I am trying to get certain values from an array but got stuck. Here is how the array looks:
array(2) {
[0]=>
array(2) {
["attribute_code"]=>
string(12) "manufacturer"
["attribute_value"]=>
string(3) "205"
}
[1]=>
array(2) {
["attribute_code"]=>
string(10) "silhouette"
["attribute_value"]=>
array(1) {
[0]=>
string(3) "169"
}
}
}
So from it I would like to have attribute_values, and insert it into a new array, so in this example I need 205 and 169. But the problem is that attribute_value can be array or string. This is what I have right now but it only gets me the first value - 205.
foreach ($array as $k => $v) {
$vMine[] = $v['attribute_value'];
}
What I am missing here?
Thank you!
If sometimes, attribute_value can be an array, and inside it the values, you can just check inside the loop (Provided this is the max level) using is_array() function. Example:
$vMine = array();
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) { // check if its an array
// if yes merge their contents
$vMine = array_merge($vMine, $v['attribute_value']);
} else {
$vMine[] = $v['attribute_value']; // if just a string, then just push it
}
}
I suggest you to use array_map instead of for loop. You can try something like this..
$vMine = array_map(function($v) {
return is_array($v['attribute_value']) ? current($v['attribute_value']) : $v['attribute_value'];
}, $arr);
print '<pre>';
print_r($vMine);
Try the shorthand version:
foreach ($array as $k => $v) {
$vMine[] = is_array($v['attribute_value']) ? current($v['attribute_value']):$v['attribute_value'];
}
or the longer easier to understand version, both is the same:
foreach ($array as $k => $v) {
if(is_array($v['attribute_value'])) {
$vMine[] = current($v['attribute_value']);
} else {
$vMine[] = $v['attribute_value'];
}
}

How to get all keys out of associative array in php

I have an associative array in php. When I am doing a die on it, then I am getting proper values as follows:
array(1) { [0]=> array(1) { [123]=> string(5) "Hello" }}
But when I am trying extract out keys of this array into an new array, then I am not able to get keys out:
$uniqueIds = array_keys($myAssociativeArray);
die(var_dump($uniqueIds));
int(0) array(1) { [0]=> int(0) }
Can any one tell me what I am doing wrong here? I want to get all the keys out of my associative array. And for this, I am referring to thread: php: how to get associative array key from numeric index?
$uniqueIds = array_keys($myAssociativeArray[0]);
<?php
function multiarray_keys($ar) {
foreach($ar as $k => $v) {
$keys[] = $k;
if (is_array($ar[$k]))
$keys = array_merge($keys, multiarray_keys($ar[$k]));
}
return $keys;
}
$result = multiarray_keys($myAssociativeArray);
var_dump($result);
?>
The following recursively gets all the keys in an associative array
function getArrayKeysFlat($array) {
if(!isset($keys) || !is_array($keys)) {
$keys = array();
}
foreach($array as $key => $value) {
$keys[] = $key;
if(is_array($value)) {
$keys = array_merge($keys,getArrayKeysFlat($value));
}
}
return $keys;
}

Categories