in which array is the value I'm looking for? - php

I have two or more than two arrays in PHP. For example:
$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
I want to find which of these arrays contains the value 5, so that I can create the output "$array1 contains 5"

try this,
$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
$f = 5;
for($n=1;$n<=3;$n++){
if(in_array($f, ${"array" . $n})){
echo "\$array$n contains $f";
}
}
Edit different variable name
$zomer = [1,5,10,15,22,28];
$halil = [1,8,12,16,25,30];
$kaya= [10,15,20,21,22];
$f = 5;
$collection = compact("zomer","halil","kaya");
foreach ($collection as $key=>$val){
if(in_array($f, $collection[$key])){
echo "\$$key contains $f";
}
}

As said #KrijnToet, it could be done easy with help of in_array() function:
if(in_array($val, $array1)) echo $val.' comes from $array1'.PHP_EOL;
Demo

Something along these lines may help:
feed the function findVal() with the arrays and a needle value you're looking for and it will return the name of the array(s) holding it.
<?php
$array1 = [1, 5, 10, 15, 22, 28];
$array2 = [1, 8, 12, 16, 25, 30];
$array3 = [10, 15, 20, 21, 22];
findVal([$array1, $array2, $array3], 30);
function findVal($arrays = [], $needle)
{
foreach ($arrays as $key => $array) {
foreach ($array as $value) {
if ($value == $needle) {
foreach ($GLOBALS as $arrayName => $value) {
if ($value === $array) {
echo 'value ' . $needle . ' found in : ' . $arrayName;
}
}
}
}
}
}
$GLOBALS — References all variables available in global scope, so we can use it to retrieve the array name(s).
demo

<?php
$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
$compacted = compact('array1', 'array2', 'array3');
$needle = 21;
$found = array_filter($compacted, function($item) use ($needle) {
return in_array($needle, $item);
});
var_export(array_keys($found));
Output:
array (
0 => 'array3',
)

Try this, using this function we can search in any number of array
$array1 = [1,5,10,15,22,28];
$array2 = [1,8,12,16,25,30];
$array3 = [10,15,20,21,22];
$findval=5;
$arrayFinal = array('array1' =>$array1 ,'array2' =>$array2 ,'array3' =>$array3 );
function searchForId($find, $array) {
foreach ($array as $key=> $value) {
if(in_array($find, $value)){
echo "\$$key contains $find";
}
}
}
searchForId($findval,$arrayFinal); //Call function

Related

Expand an associative array N-times and get all key combinations

I am trying to expand/multiply an associative array N times and get all possible key combinations.
To do it manually for two times, I would do this:
$copy = $array;
foreach ($array as $key1=>$tmp1) {
foreach ($copy as $key2=>$tmp2) {
$combos[] = array($key1,$key2);
}
}
for expanding three times:
$copy = $copy2 = $arr1;
foreach ($arr1 as $key1=>$qd1) {
foreach ($copy as $key2=>$qd2) {
foreach ($copy2 as $key3=>$qd3) {
$combos[] = array($key1,$key2,$key3);
}
}
}
how would one do this for n-times? $combos should have n-elements for each element as shown.
I looked at the other questions, but it is not quite the same here.
Finally got it:
$array = ['1' => [3, 4], '2' => [5, 6]];
$depth = 2;
function florg ($n, $elems) {
if ($n > 0) {
$tmp_set = array();
$res = florg($n-1, $elems);
foreach ($res as $ce) {
foreach ($elems as $e) {
array_push($tmp_set, $ce . $e);
}
}
return $tmp_set;
}
else {
return array('');
}
}
$output = florg($depth, array_keys($array));
What I did is basically extract the first level keys with array_keys and then created all possibles combinations thanks to https://stackoverflow.com/a/19067650/4585634.
Here's a working demo: http://sandbox.onlinephpfunctions.com/code/94c74e7e275118cf7c7f2b7fa018635773482fd5
Edit: didn't see David Winder comment, but that's basically the idea.

Php three array merge combine

$arr1 = array(1,2,3);
$arr2 = array("a","b","c");
$arr3 =array("1a","2b","3c");
How can I do the following ?
print
$one = 1,a,1a
$two = 2,b,2b
$three = 3,c,3c
Use array_map() function to map through all arrays at the same time. Like this :
$array_merged = array_map(function($v1,$v2,$v3) {
return $v1 . ','. $v2 . ',' . $v3;
}, $arr1, $arr2, $arr3);
/*
Array (
[0] => "1,a,1a",
[1] => "2,b,2b",
[2] => "3,c,3c",
)
*/
You can try this:
$arr1 = array(1,2,3);
$arr2 = array("a","b","c");
$arr3 = array("1a","2b","3c");
$i = 0;
foreach ($arr1 as $key => $value) {
$newArr[] = $value.",".$arr2[$i].",".$arr3[$i];
$i++;
}
echo implode("<br/>", $newArr);
Result:
1,a,1a
2,b,2b
3,c,3c
You can also perform this by using for loop.
Try this:
$arr1 = [1,2,3];
$arr2 = ["a","b","c"];
$arr3 = ["1a","2b","3c"];
$matrix = [$arr1, $arr2, $arr3];
var_dump(transpose($matrix));
function transpose($matrix) {
return array_reduce($matrix, function($carry, $item) {
array_walk($item, function ($value, $key) use (&$carry) {
$carry[$key][] = $value;
});
return $carry;
});
}

Access nested associative array by array of strings

So basically i would like to transform code like
$my_array = [];
$cur_string = ['a', 'b', 'c', 'd'];
$v = 'Hello world!';
To something like:
$my_array['a']['b']['c']['d'] = $v;
I tried something like:
foreach( $cur_string as $cur ) {
if ( !isset( $current[ $cur ] ) ) {
$current[ $cur ] = [];
}
$current = $current[ $cur ];
}
$current[$k] = $v;
But I know this code isn't supposed to work.. How can I do this? I don't know exact level of nesting in $cur_string array.
You can use the following method which is based on passing by reference.
/**
* Fill array element with provided value by given path
* #param array $data Initial array
* #param array $path Keys array which transforms to path
* For example, [1, 2, 3] transforms to [1][2][3]
* #param mixed $value Saved value
*/
function saveByPath(&$data, $path, $value)
{
$temp = &$data;
foreach ($path as $key) {
$temp = &$temp[$key];
}
// Modify only if there is no value by given path in initial array
if (!$temp) {
$temp = $value;
}
unset($temp);
}
Usage:
Without initial value:
$a = [];
saveByPath($a, [1, 2, 3, 4], 'value');
var_dump($a[1][2][3][4]) -> 'value';
With initial value:
$a = [];
$a[1][2][3][4] = 'initialValue';
saveByPath($a, [1, 2, 3, 4], 'value');
var_dump($a[1][2][3][4]) -> 'initialValue';
Showing both set and get functions:
$my_array = [];
$cur_string = ['a', 'b', 'c', 'd'];
$cur_string2 = ['a', 'b', 'd', 'e'];
$v = 'Hello world!';
$v2 = 'Hello world2!';
function setValue(&$array, $position, $value) {
$arrayElement = &$array;
foreach($position as $index) {
$arrayElement = &$arrayElement[$index];
}
$arrayElement = $value;
}
function getValue($array, $position) {
$arrayElement = $array;
foreach($position as $index) {
if(!isset($arrayElement[$index])) {
throw new Exception('Element is not set');
}
$arrayElement = $arrayElement[$index];
}
return $arrayElement;
}
setValue($my_array, $cur_string, $v);
setValue($my_array, $cur_string2, $v2);
var_dump($my_array);
try {
$result = getValue($my_array, $cur_string);
} catch(Exception $e) {
die($e->getMessage);
}
var_dump($result);

Split an array by key

I have an array with the following keys:
Array
{
[vegetable_image] =>
[vegetable_name] =>
[vegetable_description] =>
[fruit_image] =>
[fruit_name] =>
[fruit_description] =>
}
and I would like to split them based on the prefix (vegetable_ and fruit_), is this possible?
Currently, I'm trying out array_chunk() but how do you store them into 2 separate arrays?
[vegetables] => Array { [vegetable_image] ... }
[fruits] => Array { [fruit_image] ... }
This should work for you:
$fruits = array();
$vegetables = array();
foreach($array as $k => $v) {
if(strpos($k,'fruit_') !== false)
$fruits[$k] = $v;
elseif(strpos($k,'vegetable_') !== false)
$vegetables[$k] = $v;
}
As an example see: http://ideone.com/uNi54B
Out of the Box
function splittArray($base_array, $to_split, $delimiter='_') {
$out = array();
foreach($to_split as $key) {
$search = $key.delimiter;
foreach($base_array as $ok=>$val) {
if(strpos($ok,$search)!==false) {
$out[$key][$ok] = $val;
}
}
return $out;
}
$new_array = splittArray($array,array('fruit','vegetable'));
It is possible with array_reduce()
$array = ['foo_bar' => 1, 'foo_baz' => 2, 'bar_fee' => 6, 'bar_feo' => 9, 'baz_bee' => 7];
$delimiter = '_';
$result = array_reduce(array_keys($array), function ($current, $key) use ($delimiter) {
$splitKey = explode($delimiter, $key);
$current[$splitKey[0]][] = $key;
return $current;
}, []);
Check the fiddle
Only one thins remains: you are using different forms (like "vegetable_*" -> "vegetables"). PHP is not smart enough to substitute language (that would be English language in this case) transformations like that. But if you like, you may create array of valid forms for that.
Use explode()
$arrVeg = array();
$arrFruit = array();
$finalArr = array();
foreach($array as $k => $v){
$explK = explode('_',$k);
if($explK[0] == 'vegetable'){
$arrVeg[$k] = $v;
} elseif($explK[0] == 'fruit') {
$arrFruit[$k] = $v;
}
}
$finalArr['vegetables'] = $arrVeg;
$finalArr['fruits'] = $arrFruit;
Use simple PHP array traversing and substr() function.
<?php
$arr = array();
$arr['vegetable_image'] = 'vegetable_image';
$arr['vegetable_name'] = 'vegetable_name';
$arr['vegetable_description'] = 'vegetable_description';
$arr['fruit_image'] = 'fruit_image';
$arr['fruit_name'] = 'fruit_name';
$arr['fruit_description'] = 'fruit_description';
$fruits = array();
$vegetables = array();
foreach ($arr as $k => $v) {
if (substr($k, 0, 10) == 'vegetable_') {
$vagetables[$k] = $v;
}
else if (substr($k, 0, 6) == 'fruit_') {
$fruits[$k] = $v;
}
}
print_r($fruits);
print_r($vagetables);
Working Example

php 2 foreach result mixed

I have 2 array datas, ("a","b","c") and ("x","y","z"), how to mixed them and out put a result as (ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz)? (each $array1 + $array2 combine into a new words).
$array1 = array("a","b","c");
foreach($array1 as $data1){
}
$array2 = array("x","y","z");
foreach($array2 as $data2){
}
//$output = '(ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz)';
$array = array();
$array1 = array("a","b","c");
$array2 = array("x","y","z");
foreach($array1 as $data1){
foreach($array2 as $data2){
$array[] = '('.$data1.$data2.')';
}
}
echo implode('|', $array);
<?php
$array1 = array("a","b","c");
$array2 = array("x","y","z");
$array3 = array();
foreach($array1 as $data1){
foreach($array2 as $data2){
$array3[] = "($data1$data2)";
}
}
echo implode('|', $array3);
// (ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz)
You'll want to use a nested loop:
$items = array();
foreach($array1 as $a)
{
foreach($array2 as $b)
{
$items[] = '(' . $a . $b . ')';
}
}
echo implode('|', $items); // (ax)|(ay)|(az)|(bx)|(by)|(bz)|(cx)|(cy)|(cz)

Categories