How to search partially array value in PHP - php

First of all - thx for ansvers.
I have got 2 arrays:
For example:
['a' => abc, 'b' => cde]
And second one
['fcb' => cde, 'avm' => efg]
Need to have true of 'b' and 'cde'.
How get a certain similarity for this?

I may be falling into a trap; but, you can compute the intersection (common values) and loop them and search for the key:
$result = array_intersect($array1, $array2);
foreach($result as $val) {
echo "$val found in array1 at key: " . array_search($val, $array1)."<br>\n";
echo "$val found in array2 at key: " . array_search($val, $array2)."<br>\n";
}
See Example.

Assuming that you want to do string search on both keys and values based on your requirement that 'b' should match in both cases:
$a = ['a' => 'abc', 'b' => 'cde'];
$b = ['fcb' => 'cde', 'avm' => 'efg'];
function search($needle, $haystack)
{
foreach(array_merge($haystack, array_keys($haystack)) as $value)
{
if (strpos($value, $needle) !== FALSE)
{
return TRUE;
}
}
return FALSE;
}
echo (int) search('b', $a);
echo (int) search('b', $b);
echo (int) search('z', $a);
echo (int) search('z', $b);
echo (int) search('cde', $a);
echo (int) search('cde', $b);
Output:
110011

Related

PHP: how to detect items with and without values in foreach

Consider this example:
$arr = array('bla', 'foo', 'baz' => 2);
foreach ($arr as $arrKey => $arrValue) {
echo $arrValue . PHP_EOL;
}
This will output:
bla
foo
2
But how can I detect within the foreach loop which items have had a value and which ones have had a key + value defined?
The reason you are confused is you don't have a complete understanding of how arrays work.
$arr = array('bla', 'foo', 'baz' => 2);
This evaluates to an array of 3, all of them having values.
That's its output:
Array
(
[0] => bla
[1] => foo
[baz] => 2
)
When you push a value without specifying a key, it's key is the first available numeric index.
That's why in your case, the indexes 0 and 1 get the values 'bla' and 'foo'. 2 is the third value you push to the array, and its value isn't 2 but 'baz', because that's the value you specify.
This line:
$arr = array('bla', 'foo', 'baz' => 2);
and this one:
$arr = array(0 => 'bla', 1 => 'foo', 'baz' => 2);
are the exact same thing.
If you want an empty key, do this:
$arr = array('bla', 'foo', 'baz' => '');
Output:
Array
(
[0] => bla
[1] => foo
[baz] =>
)
Your array would work better as:
$arr = ['bla', 'foo', ['baz' => 2]];
Then you could construct your foreach like so:
foreach ($arr as $a) {
if (is_array($a)) {
foreach ($a as $key => $val) {
echo $val . PHP_EOL;
}
} else {
echo $a . PHP_EOL;
}
}
You can test if the $arrKey is not numeric then display it.
Try this :
$arr = array('bla', 'foo', 'baz' => 2);
foreach ($arr as $arrKey => $arrValue) {
if(is_numeric($arrKey))
echo $arrValue . PHP_EOL;
else
echo $arrKey." ".$arrValue . PHP_EOL;
}
This will output :
bla
foo
baz 2
If there is no associated key for any element, it will have default numeric keys such as 0, 1, 2... etc.
So, array('bla', 'foo', 'baz' => 2) is exactly array(0=>'bla', 1=>'foo', 'baz' => 2).
So, if you want to single out elements having associated key, you can try like,
$arr = array('bla', 'foo', 'baz' => 2);
foreach ($arr as $arrKey => $arrValue) {
if(!is_numeric($arrKey))
{
//do your code here
}
else
{
//additional code
}
}
if key is not mentioned, php will assign default key for value.
eg : $arr = array('bla', 'foo', 'baz' => 2); will be
$arr = array(0=>'bla', 1=>'foo', 'baz' => 2);
if you want to separate, then you can check whether key is numeric or not.
Othercase - check both numeric and index.
$arr = array('bla', 'foo', 'baz' => 2,'test');
$cnt = 0;
foreach ($arr as $arrKey => $arrValue) {
if(is_numeric($arrKey) && $cnt == $arrKey) {
echo $arrValue . PHP_EOL;
$cnt = $cnt + 1;
} else {
echo $arrKey . ':' .$arrValue . PHP_EOL;
}
}
Edited : Array integer value index is already present, then just assign the cnt value so it will autoincrement from there..
if(is_numeric($arrKey)) {
if($cnt == $arrKey) {
echo $arrValue . PHP_EOL;
$cnt = $cnt + 1;
} else {
echo $arrKey . ':' .$arrValue . PHP_EOL;
$cnt = $arrKey;
}
} else {
echo $arrKey . ':' .$arrValue . PHP_EOL;
}

Is there an elegant way to start a foreach from the second index and then do the rest?

If I have the following:
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $v) {
echo $v;
}
How can I make it output:
2, 1, 3, 17
Quoting the PHP Manual on Language Operators:
The + operator returns the right-hand array appended to the left-hand
array; for keys that exist in both arrays, the elements from the
left-hand array will be used, and the matching elements from the
right-hand array will be ignored.
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
$b = array_values($a);
echo implode(', ', array($b[1], $b[0]) + $b), PHP_EOL;
Output:
2, 1, 3, 17
$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
foreach (array_slice($values, 2) as $v){
echo "$v, "
}
If you care about last comma...
$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
$lastIndex = count($values) - 1;
foreach (array_slice($values, 2) as $k => $v){
echo $v;
if ($k != $lastIndex){
echo ", ";
}
}
You could probably do something like:
<?php
$my_array = array(...);
$keys = array_keys($my_array);
$second_key = $keys[1]; // if your array can be whatever size, probably want to check that first
echo $my_array[$second_key];
foreach ($my_array as $key => $value) {
if ($key == $second_key) {
continue;
}
echo $value;
}
?>

How do you append to an existing array in PHP after comparing with another array based on their keys?

Array1
(
[a]=>1; [b]=>2; [c]=>3
)
Array2
(
[a]=>1;[b] =>1
)
Required result:
Array1
(
[a]=>2; [b]=>3; [c]=>3
)
How do i append Array1 with the values of Array2 based on their key? Thanks.
You can try something like this:
foreach($array2 as $key2 => $val2){
if(key_exists($key2, $array1)) {
$array1[$key2] += $val2;
} else {
$array1[$key2] = $val2;
}
}
Part of the issue would be that array 1 may not have all of the same keys as array 2. So, an array of all keys from both original arrays is needed, then loop through those keys, check if it exists in either original array, and finally add it to the final combined array.
<?php
$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('a' => 1, 'b' => 2, 'd' => 3);
$finalarr = array();
$arrkeys = array_merge(array_keys($array1), array_keys($array2));
$arrkeys = array_unique($arrkeys);
foreach($arrkeys as $key) {
$finalarr[$key] = 0;
if (isset($array1[$key])) {
$finalarr[$key] += $array1[$key];
}
if (isset($array2[$key])) {
$finalarr[$key] += $array2[$key];
}
}
print_r($finalarr);
?>
foreach($array1 as $key=>$value){
if(isset($array2[$key])){
$array1[$key] = $array1[$key] + $array2[$key];
}
}
Not the most elegant way, which would use array_walk or array_map, but I like to see and know exactly what's going on. This will give you what you are looking for.
First sum the values of the common keys and after that, add the others key in the other array:
foreach ($array2 as $k2 => $a2){
if (isset($array1[$k2])){
$array1[$k2]+=$a2;
unset($array2[$k2]);
}
}
$array1 += $array2;
Something like:
$result = array();
function ParseArray(array $array, array &$result)
{
foreach ($array as $k => $v) {
if (!array_key_exists($k, $result) {
$result[$k] = $v;
} else {
$result[$k] += $v;
}
}
}
ParseArray($Array1, $result);
ParseArray($Array2, $result);
print_r($result);
You should read about PHP array functions.
$array1 = array(
'a' => 1,
'b' => 2,
'c' => 3,
);
$array2 = array(
'a' => 1,
'b' => 1,
);
array_walk(
$array1,
function (&$value, $key) use ($array2) {
$value += (isset($array2[$key])) ? $array2[$key] : 0;
}
);
var_dump($array1);

PHP: Looking for key in array and returning boolean result

In my code below, I want the PHP to look for "NUMBER" with a value of 2 and say in Boolean whether it exists, however it's not working:
<?
$array[] = array('NUMBER' => 1, 'LETTER' => 'A');
$array[] = array('NUMBER' => 2, 'LETTER' => 'B');
$array[] = array('NUMBER' => 3, 'LETTER' => 'C');
echo (in_array(array('NUMBER' => 2), $array)) ? '1' : '0'; // (expected: 1; actual: 0)
?>
Can anyone tell me where I'm going wrong please? Thanks in advance.
in_array()` compares the given values with the values of the array. In your case every entry of the array has two values, but the given array only contains one, thus you cannot compare both this way. I don't see a way around
$found = false;
foreach ($array as $item) {
if ($item['NUMBER'] == 2) {
$found = true;
break;
}
}
echo $found ? '1' : '0';
Maybe (especially with php5.3) you can build something with array_map() or array_reduce(). For example
$number = 2;
echo array_reduce($array, function ($found, $currentItem) use ($number) {
return $found || ($currentItem['NUMBER'] == $number);
}, false) ? '1' : '0';
or
$number = 2;
echo in_array($number, array_map(function ($item) {
return $item['NUMBER'];
}, $array) ? '1' : '0';
Problem is that you're searching for partial element of index 1 of $array.
But if you search:
echo (in_array(array('NUMBER' => 2, 'LETTER' => 'B'), $array))
then it will return 1.
EDIT: Use array_filter if you want to perform above task like this:
$arr = array_filter($array, function($a) { return (array_search(2, $a) == 'NUMBER'); } );
print_r($arr);
OUTPUT
Array
(
[1] => Array
(
[NUMBER] => 2
[LETTER] => B
)
)

compare arrays : one array is contained in the second array (key+value)

i want to check if one array is contained in the second array ,
but the same key and the same values,
(not need to be equal, only check that all the key and value in one array is in the second)
the simple thing that i do until now is :
function checkSameValues($a, $b){
foreach($a as $k1 => $v1){
if($v1 && $v1 != $b[$k1]){
return false;
break;
}
}
return true;
}
Is there a simpler(faster) way to check this ?
thanks
I would do
$array1 = array("a" => "green", "b" => "blue", "c" => "white", "d" => "red");
$array2 = array("a" => "green", "b" => "blue", "d" => "red");
$result = array_diff_assoc($array2, $array1);
if (!count($result)) echo "array2 is contained in array";
What about...
$intersect = array_intersect_assoc($a, $b);
if( count($intersect) == count($b) ){
echo "yes, it's inside";
}
else{
echo "no, it's not.";
}
array_intersect_assoc
array_intersect_assoc() returns an array containing all the values of array1 that are present in all the arguments.
function checkSameValues($a, $b){
if ( in_array($a,$b) ) return true;
else return false;
}
This obviously only checks depth=1, but could easily be adapted to be recursive:
// check if $a2 is contained in $a1
function checkSameValues($a1, $a2)
{
foreach($a1 as $element)
{
if($element == $a2) return true;
}
return false;
}
$a1 = array('foo' => 'bar', 'bar' => 'baz');
$a2 = array('el' => 'one', 'another' => $a1);
var_dump(checkSameValues($a2, $a1)); // true

Categories