Find various values in array? - php

I want to find the first occurrence of any of several values in an array.
$sentence = array(I, want, to, go, to, the, market);
if(in_array(array('swim','fly','go'), $sentence)) {
// Should return KEY = 3 as 'go' was found in the third key of the array
}
I'm sure this must be fairly common, how can it be done?

http://tr.php.net/manual/en/function.array-keys.php
I think more specifically you are looking for this type of functionality?
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
The above example will output:
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => size
)

first of all you should read manual properly of in_array function , you were passing parameters in wrong order
$sentence = array(I, want, to, go, to, the, market);
$found_key = array();
foreach($sentence as $key => $word)
{
if(in_array($word,array('swim','fly','go')))
{ $found_keys[] = $key;}
}
print_r($found_keys);
I hope this is what you need

Please use this function array_search it will return key of the element if element found in the array
Example
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;

array_keys would work a treat.
$keys = array_keys($sentence,array('swim','fly','go');
Then $keys will be a list of keys where swim, fly and go appear in $sentence
Just as the code below will return a list of keys that have empty values
$array = array('one','','three');
$keys = array_keys($array,"");

function find_in_array($needles,$array) {
$pos = false;
foreach ($needles as $key => $value) {
if (in_array($value, $array)) {
if(!$pos || array_search($value, $array) < $pos) {
$pos = array_search($value, $array);
}
}
}
return $pos;
}
echo find_in_array($values,$sentence);
This is what I am using right now, I'm testing array_keys as suggested by Darian Brown

Related

Filter 2d array to keep all rows which contain a specific value

I have a two dimensional haystack array like this:
[
4 => [0, 1, 2, 3, 10],
1 => [0, 1, 2, 3, 10],
2 => [0, 1, 2, 3],
3 => [0, 1, 2, 3]
]
Let's say that I have a search value of $x = 10.
How can I search in above array and get an array index which contains $x.
In my current example, subarrays with key 4 and 1 contain value of $x -- I need those 2 subarrays.
You could loop then use array_search()
$array = array(...); // Your array
$x = 10;
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
echo 'Found on Index ' . $key . '</br>';
}
}
Or if you need the arrays with those index
$array = array(...); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (array_search($x, $value)) {
$result[] = $array[$key]; // push to result if found
}
}
print_r($result);
You can use array_filter() to keep only the array that contains the value you want:
$array = array(
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3, 10),
array(0, 1, 2, 3),
array(0, 1, 2, 3)
);
$x = 10;
$out = array_filter($array, function($arr) use($x) {
return in_array($x, $arr);
});
print_r($out);
Output:
Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
[1] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 10
)
)
You can use as well in_array
$array = array(); // Your array
$x = 10;
$result = array(); // initialize results
foreach ($array as $key => $value) {
if (in_array($x, $value)) {
$result[] = $array[$key]; //
}
}
print_r($result)
You can use array_search() function to search the value in array..
Link: http://php.net/manual/en/function.array-search.php
For Exp:
$x = 10; // search value
$array = array(...); // Your array
$result = array(); // Result array
foreach ($array as $key => $value)
{
if (array_search($x, $value))
{
$result[] = $array[$key]; // push the matched data into result array..
}
}
print_r($result);
You can use array_search();
doc: http://www.php.net/manual/en/function.array-search.php

Merge keys of an array based on values

I want to merge the keys of array based on values. This is my array.
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 0
[6] => 2
[7] => 2
)
I want output as
Array
(
[1,2,3] => 1
[4,6,7] => 2
[5] => 0
)
I have been brain storming entire day but couldn't find a solution. Any hint would be much appreciated.
WHAT I HAVE TRIED:
for($i=2;$i<=count($new);$i++){
if ($new[$i-1][1]==$new[$i][1]){
$same .= $new[$i-1][0].$new[$i][0];
}
}
echo $same;
But I am stucked. I am comparing the keys one by one but it's very complicated. I don't need the code. I only need the hint or logic. Anyone kind enough?
<?php
$old_arr = ["1"=>1,"2"=>1,"3"=>1,"4"=>2,"5"=>0,"6"=>2,"7"=>2];
$tmp = array();
foreach($old_arr as $key=>$value)
{
if(in_array($value, $tmp)){
$index = array_search($value, $tmp);
unset($tmp[$index]);
$tmp[$index.",".$key] = $value;
}else{
$tmp[$key] = $value;
}
}
ksort($tmp);
echo "<pre>";
print_r($tmp);
echo "</pre>";
?>
https://eval.in/529314
You can loop through array elements and create a new array with new structure. Please check the below code it may help you
$old_array = array(1=> 1,2 => 1,
3=> 1,
4 => 2,
5 => 0,
6 => 2,
7 => 2
);
$new_array = array();
foreach($old_array as $key => $value)
{
if(in_array($value,$new_array))
{
$key_new = array_search($value, $new_array);//to get the key of element
unset($new_array[$key_new]); //remove the element
$key_new = $key_new.','.$key; //updating the key
$new_array[$key_new] = $value; //inserting new element to the key
}
else
{
$new_array[$key] = $value;
}
}
print_r($new_array);
$arr = array(1 => 1, 2 => 1, 3 => 1, 4 => 2, 5 => 0, 6 => 2, 7 => 2);
$tmp = array();
foreach ($arr as $key => $val)
$tmp[$val][] = $key;
$new = array();
foreach ($tmp as $key => $val)
$new[implode(',', $val)] = $key;
First loop the original array through, creating a temporary array, where your original values are keys and values are the original keys as an array.
Then loop the temporary array, creating the new array, where the temporary array's values are imploded as keys.
There's no way to have an array of keys to a single value, but the other way around:
function flipWithKeyArray($arr){
$result = array();
foreach($arr as $key => $val){
if(!isset($result[$val]))
$result[$val] = array();
$result[$val][] = $key;
}
return $result;
}
This will flip your array and declare one array per value of your old array and then push the keys with the same value into each list.
For an array like this:
array(1=>1, 2=>1, 3=>1, 4=>2, 5=>2, 6=>2)
The result will look like this:
array(1=>array(1,2,3), 2=>array(4,5,6))
Hope it fits your need.

Merge multiple arrays from one array

How to merge multiple arrays from a single array variable ? lets say i have this in one array variable
Those are in one variable ..
$array = array(array(1), array(2));
Array
(
[0] => 1
)
Array
(
[0] => 2
)
how to end up with this
Array
(
[0] => 1
[1] => 2
)
This is the PHP equivalent of javascript Function#apply (generate an argument list from an array):
$result = call_user_func_array("array_merge", $input);
demo: http://3v4l.org/nKfjp
Since PHP 5.6 you can use variadics and argument unpacking.
$result = array_merge(...$input);
It's up to 3x times faster than call_user_func_array.
This may work:
$array1 = array("item1" => "orange", "item2" => "apple", "item3" => "grape");
$array2 = array("key1" => "peach", "key2" => "apple", "key3" => "plumb");
$array3 = array("val1" => "lemon");
$newArray = array_merge($array1, $array2, $array3);
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
array_merge can do the job
$array_meged = array_merge($a, $b);
after the comment
If fixed indexs you can use:
$array_meged = array_merge($a[0], $a[1]);
A more generic solution:
$array_meged=array();
foreach($a as $child){
$array_meged += $child;
}
$resultArray = array_merge ($array1, $array1);
$result = array();
foreach ($array1 as $subarray) {
$result = array_merge($result, $subarray);
}
// Here it is done
Something good to read:
http://ca2.php.net/manual/en/function.array-merge.php
Recursive:
http://ca2.php.net/manual/en/function.array-merge-recursive.php
$arr1 = array(0=>1);
$arr2 = array(0=>2);
$merged = array_merge($arr1,$arr2);
print_r($merged);
array_merge is what you need.
$arr = array_merge($arr1, $arr2);
Edit:
$arr = array_merge($arr1[0], $arr1[1]);

Search multidimensional php array by key

I have a multidimensional php array like this
Array
(
[0] => Array
(
[size] => M
[colour] => black
[quantity] => 10
)
[1] => Array
(
[size] => S
[colour] => blue
[quantity] => 10
)
)
and i have another array like this
Array
(
[size] => M
[colour] => black
)
How do i transverse to first array to find the array that matches the second one?.
Am totally clueless on how to go about this. Thanks
Taking a different approach:
$multiArray = array(array('size' => 'M',
'color' => 'black',
'quantity' => '10'),
array('size' => 'S',
'color' => 'blue',
'quantity' => 10));
$otherArray = array('size' => 'S',
'color' => 'blue',
'quantity' => 10)
$message = "Match not found!";
foreach($multiArray as $array) {
$result = array_diff($array, $otherArray);
if(isset($result['size']) or isset($result['color'))
continue;
else
$message = "Found a match!\n Size: {$array['size']}\n Color: {$array['color']}\n Quantity: {$array['quantity']}";
}
echo $message;
This solution seems correct to me because from your example I'm guessing you are trying to find the quantity. Therefore, the array_diff will return the quantity in the result regardless, resulting in the need to check for just size and color for a match.
Consider first array is "mainarray" and second one is "comparearray"
$result = array();
foreach($mainarray as $marray)
{
if($marray['size'] == $comparearray['size'] && $marray['colour'] == $comparearray['colour'])
{
$result = $marray;
//echo "match found";
}
}
note: if compare array is single array it is applicable. if that also multidimension array you should put foreach for that array also.
Try this one
<?php
$arr1 = array(array("size"=>"M","colour" => "black"),array("size"=>"S","colour" => "blue"));
$arr2 = array("size"=>"M","colour" => "black");
print_r($arr1);
print_r($arr2);
foreach($arr1 as $array)
{
if($array['size'] == $arr2['size'] && $array['colour'] == $arr2['colour'])
{
echo "matches";
}
}
?>
working example http://codepad.org/iQPxSHKd
Try
$result = array();
foreach ($multi_array as $arr) {
if ($arr['size'] == $one_dimen_arr['size'] && $arr['colour'] == $one_dimen_arr['colour']) {
$result = $arr;
break;
}
}
For Example:
$array1 is your First array and $array2 is your Second array. Then :
$result = array();
foreach ($array1 as $subarray)
{
$check = array_diff($subarray, $array2);
if (empty($check)) {
$result = $subarray;
}
}

How can I compare the rows in two 2d arrays? [duplicate]

This question already has answers here:
Get difference between associative rows of two 2-dimensional arrays
(5 answers)
Closed last year.
It seems that every PHP function I read about for comparing arrays (array_diff(), array_intersect(), etc) compares for the existence of array elements.
Given two multidimensional arrays with identical structure, how would you list the differences in values?
Example
Array 1
[User1] => Array ([public] => 1
[private] => 1
[secret] => 1
)
[User2] => Array ([public] => 1
[private] => 0
[secret] => 0
)
Array 2
[User1] => Array ([public] => 1
[private] => 0
[secret] => 1
)
[User2] => Array ([public] => 1
[private] => 0
[secret] => 0
)
Difference
[User1] => Array ([public] => 1
[private] => 0 //this value is different
[secret] => 1
)
So my result would be - "Of all the users, User1 has changed, and the difference is that private is 0 instead of 1."
One way is to write a function to do something similar to this..
function compareArray ($array1, $array2)
{
foreach ($array1 as $key => $value)
{
if ($array2[$key] != $value)
{
return false;
}
}
return true;
}
You could easily augment that function to return an array of differences in the two..
Edit - Here's a refined version that more closely resembles what you're looking for:
function compareArray ($array1, $array2)
{
var $differences;
foreach ($array1 as $key => $value)
{
if ($array2[$key] != $value)
{
$differences[$key][1] = $value;
$differences[$key][2] = $array2[$key];
}
}
if (sizeof($differences) > 0)
{
return $differences;
}
else
{
return true;
}
}
I think this does what you're looking for.
Using your sample data, doing a loop on the outer arrays, then using array_diff_assoc on the users each time through. (Note, this assumes that when there's a difference, array_diff_assoc returns the value from the second array passed in, which it seems to do).
<?php
$user1 = array("public" => 1, "private" => 1, "secret" => 1);
$user2 = array("public" => 1, "private" =>1, "secret" => 1);
$array1 = array ("user 1"=>$user1, "user 2"=>$user2);
$user1 = array("public" => 1, "private" => 0, "secret" => 1);
$user2 = array("public" => 1, "private" => 1, "secret" => 1);
$array2 = array("user 1"=>$user1, "user 2"=>$user2);
$results = array();
foreach ( $array1 as $user => $value )
{
$diff = array_diff_assoc( $array1[$user], $array2[$user] );
if ($diff) {
array_push($results,array($user=>$diff));
}
}
print_r($results);
?>
It returns:
Array
(
[0] => Array
(
[user 1] => Array
(
[private] => 1
)
)
)
Try this function:
function arrayDiff($array1, $array2)
{
if (!is_array($array1) || !is_array($array2)) {
return false;
}
foreach ($array1 as $key => $val) {
if (array_key_exists($key, $array2) && gettype($val) != "array" && $val === $array2[$key]) {
unset($array1[$key]);
continue;
}
if (is_array($val)) {
$val = diff($val, $array2[$key]);
if ($val !== false) {
$array1[$key] = $val;
}
}
}
return $array1;
}
$array1 = array(
array(
array('foo', 'bar', 'baz'),
0
)
);
$array2 = array(
array(
array('foo', 'bar')
)
);
var_dump(diff($array1, $array2));
If you're looking for differences in the values, how about array_diff_assoc. The http://us2.php.net/manual/en/function.array-diff-assoc.php">php manual says it "returns an array containing all the values from array1 that are not present in any of the other arrays" and gives the following example:
In this example you see the "a" =>
"green" pair is present in both arrays
and thus it is not in the ouput from
the function. Unlike this, the pair 0
=> "red" is in the ouput because in the second argument "red" has key
which is 1
<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
The above example will output:
Array
(
[b] => brown
[c] => blue
[0] => red
)
Is this what you're looking for?

Categories