I was using a code like that:
$a = [];
$a['a'] = 1;
$text1 = [];
foreach ($b as $item)
{
$text1[] = $item['1'];
}
$a['text1'] = implode(',', $text1);
$text2 = [];
foreach ($b as $item)
{
$text2[] = $item['2'];
}
$a['text2'] = implode(',', $text2);
my colleague rewitten it like that:
$a = [];
$a['a'] = 1;
$a['text1'] = call_user_func(function() use ($b) {
$text1 = [];
foreach ($b as $item)
{
$text1[] = $item['1'];
}
return implode(',', $text1);
}();
$a['text2'] = call_user_func(function() use ($b) {
$text2 = [];
foreach ($b as $item)
{
$text2[] = $item['2'];
}
return implode(',', $text2);
}();
his reason: it increases encapsulation, and in my first example there will be "strolling" variables ($text1, $text2) unless I unset them.
Yes, I agree with your colleague - it makes sense to use closures to encapsulate code.
However, the entire thing you have there can be simplified to this:
<?php
$a = [
'a' => 1,
'text1' => implode(',', array_column($b, '1')),
'text2' => implode(',', array_column($b, '2')),
];
For reference, see:
http://php.net/manual/en/function.array-column.php
Related
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
I am adding other value array inside foreach loop which working fine for me.
$i = true;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
echo $value . '<br />';
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $key => & $other_value) {
$array[] = $other_value;
}
}
$i = false;
}
Output
red
blue
white
yellow
but i want to reshuffle array value inside foreach loop need output like below
red
white
yellow
blue
You won't be able to do it on $array without some serious array_slice()ing. So, just assign to another array $result and you will get the $other array inserted between the first and second elements of $array:
$i = true;
$array = array('red', 'blue');
foreach($array as $value) {
$result[] = $value; // here...
if ($i === true) {
$others = array('white', 'yellow');
foreach($others as $other_value) {
$result[] = $other_value; // and here...
}
}
$i = false;
}
If needed (for whatever reason) $array = $result;
A cool solution would be like this:
$array = array('red', 'blue');
$others = array('white', 'yellow');
$temp = array_combine($array,$others);
$final = array();
foreach($temp as $key => $value) {
array_push($final,$key,$value);
}
$array = $final;
$i = true;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
echo $value . '<br />';
if ($i === true) {
$a1= $array;
$a2= array($value);
$result=array_diff($a1,$a2);
$others = array('white', 'yellow');
$array = array_merge($others,$result);
}
$i = false;
}
see output
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
I need to replace multiple sections of a string based on their indices.
$string = '01234567890123456789';
$replacements = array(
array(3, 2, 'test'),
array(8, 2, 'haha')
);
$expected_result = '012test567haha0123456789';
Indices in $replacements are expected not to have overlaps.
I have been trying to write my own solution, split the original array into multiple pieces based on sections which needs to be replaced or not, and finally combine them:
echo str_replace_with_indices($string, $replacements);
// outputs the expected result '012test567haha0123456789'
function str_replace_with_indices ($string, $replacements) {
$string_chars = str_split($string);
$string_sections = array();
$replacing = false;
$section = 0;
foreach($string_chars as $char_idx => $char) {
if ($replacing != (($r_idx = replacing($replacements, $char_idx)) !== false)) {
$replacing = !$replacing;
$section++;
}
$string_sections[$section] = $string_sections[$section] ? $string_sections[$section] : array();
$string_sections[$section]['original'] .= $char;
if ($replacing) $string_sections[$section]['new'] = $replacements[$r_idx][2];
}
$string_result = '';
foreach($string_sections as $s) {
$string_result .= ($s['new']) ? $s['new'] : $s['original'];
}
return $string_result;
}
function replacing($replacements, $idx) {
foreach($replacements as $r_idx => $r) {
if ($idx >= $r[0] && $idx < $r[0]+$r[1]) {
return $r_idx;
}
}
return false;
}
Is there any more effective way to achieve the same result?
The above solution doesn't look elegant and feels quite long for string replacement.
Use this
$str = '01234567890123456789';
$rep = array(array(3,3,'test'), array(8,2,'haha'));
$index = 0;
$ctr = 0;
$index_strlen = 0;
foreach($rep as $s)
{
$index = $s[0]+$index_strlen;
$str = substr_replace($str, $s[2], $index, $s[1]);
$index_strlen += strlen($s[2]) - $s[1];
}
echo $str;
I have 2D array and want to get all values which are at same index say at index '1'. what is the best way to get that as a new array.
Example: we have array(array(1,2,3), array(5,6,7)), the result must be array(2, 6).
Thanks
A simple function would do the trick:
function foobar($array, $index) {
$result = array();
foreach($array as $subarray) {
if(isset($subarray[$index])) {
$result[] = $subarray[$index];
}
}
return $result;
}
Or you can just use array_map (requires PHP 5.3):
array_map(function($array) { return $array[1]; }, $input);
$sample = array(array(1,2,3),
array(4,5,6),
array(7,8,9)
);
$index = 1;
$result = array_map(function($value) use($index) { return $value[$index]; }, $sample);
var_dump($result);
$input = array(
array(1,2,3),
array(5,6,7)
);
$output = array();
foreach ( $input as $data ) {
$output[] = $data[1];
}
$myarray=array(array(1,2,3), array(5,6,7));
$index=1;
$result=array();
foreach($myarray as $a) $result[]=$a[$index];
print_r($result);