Checking value in an multi-dim array? - php

My array is like:
Array
(
[0] => Array
(
[id] => 6
[name] => Name1
)
[1] => Array
(
[id] => 7
[name] => Name2
)
)
How can I check any perticular value of name exists in this multi-dimentional array?

function checkName($haystack, $needle) {
foreach($haystack as $hay) {
if($hay['name'] == $needle) {
return true;
}
}
return false;
}

Iterate.
function multi_in_array($name, $array) {
foreach ($array as $sub_array) {
if (in_array($name, $array)) {
return true;
}
}
return false;
}

perhaps you're looking for in_array function?

With that structure, your only option is essentially a linear search:
$found = null;
foreach ($arr as $idx => $elem) {
if ($elem['name'] == $searchName) {
$found = $idx;
}
}
if ($found !== null) {
echo "Found $searchName at $idx.";
}

This function will help you,
<?php
function multi_dim_array_search($array,$col,$val)
{
foreach($array as $elem)
if($elem[$col] == $val)
return true;
return false;
}
$array = array(
array('id' => 1,'name' => 'Name1'),
array('id' => 2,'name' => 'Name2')
);
//usage
var_dump(multi_dim_array_search($array,'name','Name1')); //true
var_dump(multi_dim_array_search($array,'name','Name2')); //true
var_dump(multi_dim_array_search($array,'name','Name3')); //false
?>

Related

PHP unset array value based on key

I have multidimensional array as follows,
[0] => Array
(
[data] =>
[id] => 0000
[name] => Swirl
[categories] => Array
(
[0] => Array
(
[id] => 0001
[name] => Whirl
[products] => Array
(
[0] => Array
(
[id] => 0002
[filename] => 1.jpg
)
[1] => Array
(
[id] => 0003
[filename] => 2.jpg
)
)
)
)
)
I have used the following function to find keys.
function find_parent($array, $needle, $parent = null) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$pass = $parent;
if (is_string($key)) {
$pass = $key;
}
$found = find_parent($value, $needle, $pass);
if ($found !== false) {
return $found;
}
} else if ($key === $needle) {
return $parent;
}
}
return false;
}
$parentkey = find_parent($array, 'id');
Now i need to unset the products array and replace it with another array.
how to do this.please help.
Thanks,
sarnitha
You can use a recursive function over an array:
function replaceInArray(array &$arr, $needleKey, array $replacement) {
foreach ($arr as $k => $v) {
if ($k === $needleKey) {
$arr[$k] = $replacement;
} else {
if (is_array($v)) {
replaceInArray($arr[$k], $needleKey, $replacement);
}
}
}
}
replaceInArray($sourceArr, 'products', ['id' => '0004', 'filename' => 'new.jpg']);
function replaceInArrayWithKey(array &$arr, $needleKey, array $replacementArray, $replacementKey) {
foreach ($arr as $k => $v) {
if ($k === $needleKey) {
$arr[$replacementKey] = $replacementArray;
unset($arr[$k]);
} else {
if (is_array($v)) {
replaceInArrayWithKey($arr[$k], $needleKey, $replacementArray, $replacementKey);
}
}
}
}
replaceInArrayWithKey($sourceArray, 'products', ['id' => '0004', 'filename' => 'new.jpg'], 'products_new');
You can also try using a built-in recursive iterator - https://www.php.net/manual/en/class.recursivearrayiterator.php

PHP - Get key of Associative Array

I have an array
Array(
[32] => ki
[97] => Array
(
[0] => l$
[1] => ml
[2] => 8e
)
[98] => fp
[99] => #w
[100] => lf
)
if I do array search for example:
echo array_search("fp", $array);
the output will be "98". How can I get the key if im looking for a value inside another array like "ml"? I wanted to get "97" if i search for value "ml".
I don't think there is such function for multi arrays
If you want to do it in a loop try:
foreach($array as $key => $value)
{
if(is_array($value))
{
$subarray = $value;
foreach($subarray as $subvalue)
{
if($subvalue == 'ml')
{
echo $key;
break 2;
}
}
}
else
{
if($value == 'ml')
{
echo $key;
break;
}
}
}
You could write an alternate recursive array_search function like this:
function recursive_array_search($needle, $haystack, $parent_key = null) {
foreach($haystack as $key => $value) {
$current_key = $parent_key ? $parent_key : $key;
if($needle === $value || (is_array($value) && recursive_array_search($needle, $value, $current_key) !== false)) {
return $current_key;
}
}
return false;
}
And call it like echo recursive_array_search("ml", $array);
Based on http://php.net/manual/en/function.array-search.php#91365

search and find several keys in array

public function array_searchh($needle, $haystack) {
foreach ($haystack as $key => $value) {
$current_key = '';
$current_key .= $key;
if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) {
return $current_key;
}
}
return false;
}
When I search in array return first key, but I want to search and if there same value return all keys.
[0] => Array ([id] => 1[value] => payamm)
[1] => Array ([id] =>2[value]=>payam)
[2] => Array ([id] => 25[value] => payam)
[3] => Array ([id] => 3[value] => payam)
[4] => Array ([id] => 4[value] => payam)
[5] => Array ([id] => 5[value] => 340)
In above array, I have several "payam" values. When I use above function, I just return the first (found) key but I want all matching keys.
public function array_searchh($needle, $haystack) {
foreach ($haystack as $key => $value) {
$current_key = '';
$current_key .= $key;
if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) {
$foundKeys[] = $current_key;
}
}
if (isset($foundKeys)) {
return $foundKeys;
}
return false;
}
This should return an array of all the found keys.
Instead of immediately returning the key, collect all matching keys into an array and return this array at the end of the function.
public function array_searchh($needle, $haystack) {
$returnKeys = array();
foreach ($haystack as $key => $value) {
$current_key = '';
$current_key .= $key;
if ($needle === $value OR (is_array($value) && $this->array_searchh($needle, $value) !== false)) {
$returnKeys[] = $current_key;
}
}
return (count($returnKeys) > 0) ? $returnKeys : false;
}
maybe the array_keys() function would help?

Find value and key in multidimensional array

I have the following array:
Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
I need to find if [position] => 22 exists in my array and retain the array path for further reference. Thank you.
Example of code for the solution "Ancide" provide.
$found = false;
foreach ($array as $array_item) {
if (isset($array_item['position'] && $array_item['position'] == "22")) {
$found = true;
break;
}
}
You can try this code:
$array = array
(
array (
"word" => 1,
"question" => php,
"position" => 11
),
array (
"word" => sql,
"question" => 1,
"position" => 22
)
);
foreach($array as $item)
{
foreach($item as $key=>$value)
{
if($key=="position" && $value=="22")
{
echo "found";
}
}
}
First check if they key exists using isset, then if the key exists, check that the value is equal to your compare value.
Edit: I missed that there were two arrays. To solve this, iterate through each array and do the check in each cycle. If the check is positive you know which array it is by looking at the current index.
I think there is no other solution than to loop through the array an check whether there is a key "position" and value "22"
This will solve your problem:
<?php
foreach ($array as $k => $v) {
if(isset($v['position']) && $v['position'] == 22) {
$key = $k;
}
}
echo $key;
//$array[$key]['position'] = 22
?>
Try this:
function exists($array,$fkey,$fval)
{
foreach($array as $items)
{
foreach($items as $key => $val)
if($key == $fkey and $val == $fval)return true;
}
return false;
}
Example:
if(exists($your_array,"position",22))echo("found");
function findPath($array, $value) {
foreach($array as $key => $subArray) if(subArray['position'] === $value) return $key;
return false; // or whatever if not found
}
echo findPath($x, 22); // returns 1
$x= Array (
[0] => Array (
[word] => 1
[question] => php
[position] => 11
)
[1] => Array (
[word] => sql
[question] => 1
[position] => 22
)
)
Try with this function:
function findKey($array, $mykey) {
if(array_key_exists($mykey, $array))
return true;
foreach($array as $key => $value) {
if(is_array($value))
return findKey($value, $mykey);
}
return false;
}
if(findKey($search_array, 'theKey')) {
echo "The element is in the array";
} else {
echo "Not in array";
}

PHP - Find parent key of array

I'm trying to find a way to return the value of an array's parent key.
For example, from the array below I'd like to find out the parent's key where $array['id'] == "0002".
The parent key is obvious because it's defined here (it would be 'products'), but normally it'd be dynamic, hence the problem. The 'id' and value of 'id' is known though.
[0] => Array
(
[data] =>
[id] => 0000
[name] => Swirl
[categories] => Array
(
[0] => Array
(
[id] => 0001
[name] => Whirl
[products] => Array
(
[0] => Array
(
[id] => 0002
[filename] => 1.jpg
)
[1] => Array
(
[id] => 0003
[filename] => 2.jpg
)
)
)
)
)
A little crude recursion, but it should work:
function find_parent($array, $needle, $parent = null) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$pass = $parent;
if (is_string($key)) {
$pass = $key;
}
$found = find_parent($value, $needle, $pass);
if ($found !== false) {
return $found;
}
} else if ($key === 'id' && $value === $needle) {
return $parent;
}
}
return false;
}
$parentkey = find_parent($array, '0002');
Since you have a tree structure either of a BFS or DFS can do it. Since the structure is variable a recursive solution would work well. Simply return a sentinel when you find the value, then return the key in the caller.
function array_to_xml($array, $rootElement = null, $xml = null) {
$_xml = $xml;
if ($_xml === null) {
$_xml = new SimpleXMLElement($rootElement !== null ? $rootElement : '<root/>');
}
$has_int_key = 0;
foreach ($array as $k => $v) {
if (is_array($v)) {
if(is_int($k)){
$this->array_to_xml($v, $k, $_xml->addChild($rootElement));
}
else {
foreach($v as $key=>$value) {
if(is_int($key)) $has_int_key = 1;
}
if ($has_int_key) {
$this->array_to_xml($v, $k, $_xml);
} else {
$this->array_to_xml($v, $k, $_xml->addChild($k));
}
}
}
else {
$_xml->addChild($k, $v);
}
}
return $_xml->asXML();
}

Categories