How to define a range for each key in array dynamically - php

Here is my array:
$var = array('a', 'b');
Now I want to define a range for each key. For example:
5 keys set on each value of array:
echo $var[0]; // output: a
echo $var[1]; // output: a
echo $var[2]; // output: a
echo $var[3]; // output: a
echo $var[4]; // output: a
echo $var[5]; // output: b
echo $var[6]; // output: b
echo $var[7]; // output: b
echo $var[8]; // output: b
echo $var[9]; // output: b
In fact I want something like this:
$var = array( '0'=>'a', '1'=>'a', '2'=>'a', '3'=>'a', '4'=>'a',
'5'=>'b', '6'=>'b', '7'=>'b', '8'=>'b', '9'=>'b' );
But in reality I can not define a rage of keys for each value, because the values are too much. It should be noted that I can implement it via if-else statement (without array), But in this case, performance will drop dramatically. something like this:
if (0 <= $i <=4) { $var = 'a'; }
elseif (5 <= $i <=9) { $var = 'b'; }
But as I said, the values are too much and I can not define a range for each value manually. So there is any solution ? (set 5 keys for each value dynamically)

$arr = array('a', 'b');
$i = 6; // for e.g.
$var = $arr[floor($i/5)];
// output: b

This should work for you:
Just loop through your array and array_fill() your result array with each value as many times as you want, e.g.
<?php
$var = array('a', 'b');
$amount = 5;
$result = [];
foreach($var as $k => $v)
$result = $result + array_fill($k*$amount, $amount, $v);
print_r($result);
?>
output:
Array
(
[0] => a
[1] => a
[2] => a
[3] => a
[4] => a
[5] => b
[6] => b
[7] => b
[8] => b
[9] => b
)

$var = array( '0'=>'a', '1'=>'b');
$new_array = array();
foreach ($var as $key => $value) {
for($i = 0 ; $i < 5 ; $i++){
$new_array[] = $value;
}
}
echo '<pre>';
print_r($new_array);

Related

Any other better logic for this programme

Today in an interview i got the following question to solve without using any inbuilt function eg in_array and etc.I am able to solve the programme but they told me is there any better approach and also they told me the total code is only upto 7 lines.So can anyone tell me any better approach than this:-
<?php
$a = array(1,3,5,2,1,5,11,16);
$b = array(1,4,3,11,12,5,7,18);
$final = [];
for($i=0;$i<count($a);$i++){
$flag = 0;
if($i==0){
$final[] = $a[$i];
} else {
for($j=0;$j<count($final);$j++){
if($a[$i] == $final[$j]){
$flag = 1;
}
}
if($flag==0){
$final[] = $a[$i];
}
for($k=0;$k<count($final);$k++){
if($b[$i] == $final[$k]){
$flag = 1;
}
}
if($flag==0){
$final[] = $b[$i];
}
}
}
echo '<pre>';
print_r($final);
the result would be the final array which would contain unique array of both eg
Array ( [0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 2 [5] => 11 [6] => 16 [7] => 18 )
Here is how you could do it without using built-in functions: Collect the values as keys (so they are unique), and then put those keys back as values in the final array:
$a = array(1,3,5,2,1,5,11,16);
$b = array(1,4,3,11,12,5,7,18);
foreach($a as $v) $keys[$v] = 1;
foreach($b as $v) $keys[$v] = 1;
foreach($keys as $k => $v) $final[] = $k;
echo '<pre>';
print_r($final);
See it run on eval.in.
Just set the key as the value and they will overwrite. If the arrays are the same length:
foreach($a as $k => $v) {
$final[$v] = $v;
$final[$b[$k]] = $b[$k];
}
If not, then do it for each array:
foreach(array($a, $b) as $c) {
foreach($c as $v) {
$final[$v] = $v;
}
}
The order and keys won't be the same, but that wasn't stated as a requirement.

How to find unique values in array

Here i want to find unique values,so i am writing code like this but i can't get answer,for me don't want to array format.i want only string
<?php
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$unique_array = array(); // unique array
$duplicate_array = array(); // duplicate array
foreach ($array as $key=>$value){
if(!in_array($value,$unique_array)){
$unique_array[$key] = $value;
}else{
$duplicate_array[$key] = $value;
}
}
echo "unique values are:-<br/>";
echo "<pre/>";print_r($unique_array);
echo "duplicate values are:-<br/>";
echo "<pre/>";print_r($duplicate_array);
?>
You can use array_unique() in single line like below:-
<?php
$unique_array = array_unique($array); // get unique value from initial array
echo "<pre/>";print_r($unique_array); // print unique values array
?>
Output:- https://eval.in/601260
Reference:- http://php.net/manual/en/function.array-unique.php
If you want in string format:-
echo implode(',',$final_array);
Output:-https://eval.in/601261
The way you want is here:-
https://eval.in/601263
OR
https://eval.in/601279
I am baffled by your selection as the accepted answer -- I can't imagine how it can possibly satisfy your requirements.
array_count_values() has been available since PHP4, so that is the hero to call upon here.
Code: (Demo)
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$counts = array_count_values($array); // since php4
foreach ($counts as $value => $count) {
if ($count == 1) {
$uniques[] = $value;
} else {
$duplicates[] = $value;
}
}
echo "unique values: " , implode(", ", $uniques) , "\n";
echo "duplicate values: " , implode(", ", $duplicates);
Output:
unique values: raja, mahi
duplicate values: kani, yuvi
To get unique values from array use array_unique():
$array = array(1,2,1,5,10,5,10,7,9,1) ;
array_unique($array);
print_r(array_unique($array));
Output:
Array
(
[0] => 1
[1] => 2
[3] => 5
[4] => 10
[7] => 7
[8] => 9
)
And to get duplicated values in array use array_count_values():
$array = array(1,2,1,5,10,5,10,7,9,1) ;
print_r(array_count_values($array));
Output:
Array
(
[1] => 3 // 1 is duplicated value as it occurrence is 3 times
[2] => 1
[5] => 2 // 5 is duplicated value as it occurrence is 3 times
[10] => 2 // 10 is duplicated value as it occurrence is 3 times
[7] => 1
[9] => 1
)
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1)); // will print unique values
echo "<br>";
arr_count_val($arr1); // will print array with duplicate values
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
function arr_count_val($arr) {
$uni_array = arr_unique($arr1);
$count = 0;
foreach($uni_array as $n1) {
foreach($arr as $n1) {
if($n1 == $n2) {
$count++;
}
}
echo "$n1"." => "."$count"."<br>";
$count=0;
}
}
?>

How can I separate numeric array's keys from the letter keys?

Here is my code:
$arr = array();
$arr[] = 1;
$arr['txt'] = 'something';
$arr['txt2'] = 'something2';
$arr[] = 2;
$arr[] = 3;
echo '<pre>';
print_r($arr);
/* output:
1
something
something2
2
3
*/
I'm trying to change array's order and make this result:
/* expected output:
1
2
3
something
something2
*/
As you see, I need to reindex all array's items and put the numeric ones in the beginning of array. Is that possible?
How can I separate numeric array's keys from the letter keys?
Simplest way is to sort the array by key, using ksort which modifies the array in place. Use the SORT_STRING flag to get the result you seek:
ksort($myArr, SORT_STRING);
Live demo
The Correct syntax is:
- Using array values
<?php
$arr = array();
$arr[] = 1;
$arr['txt'] = 'something';
$arr['txt2'] = 'something2';
$arr[] = 2;
$arr[] = 3;
echo '<pre>';
usort($arr, function($a, $b) {
if (is_float($a)) {
if ( is_float($b)) {
return $a - $b;
}
else
return -1;
}
elseif (is_float($b)) {
return 1;
}
else {
return strcmp($a, $b);
}
});
print_r($arr);
?>
OUTPUT
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => something
[4] => something2
)
- Using array index values
<?php
$arr = array();
$arr[] = 1;
$arr['txt'] = 'something';
$arr['txt2'] = 'something2';
$arr[] = 2;
$arr[] = 3;
echo '<pre>';
usort($arr, SORT_STRING);
print_r($arr);
?>
OUTPUT
Array
(
[0] => 1
[1] => 2
[2] => 3
[txt] => something
[txt2] => something2
)
phphtml

Compare all possible combinations of pairs of elements in two arrays in PHP

I am trying to do basic binary line classification in PHP. (Programming language irrelevant, just more comfortable with PHP).
So basically I have 2 arrays of coordinates:
$classA = [ new Point(1,1), new Point(1,2), new Point(3,3), new Point(1,5) ];
$classB = [ new Point(4,1), new Point(5,2), new Point(4,1), new Point(6,6) ];
I need to iterate through these arrays and get 2 pairs of points each time (A pair consists of a point from classA and another from classB). It is important to get all possible combinations. Once a particular point is in a pair, it cannot be present in another pair.
For example the first two pairs would be:
$pair1 = [$a[0], $b[0]];
$pair2 = [$a[1], $b[1]];
To better explain myself, this is what I need:
When the first pair contains [1,1] , [4,1] all possibile combinations for the other pair are highlighted in yellow.
So far this is what I have:
$classA = [ new Point(1,1), new Point(1,2), new Point(3,3)];
$classB = [ new Point(4,1), new Point(5,2), new Point(4,1)];
$combinations = [];
$pair1 = [];
$pair2 = [];
$n = count($classA);
$m = count($classB);
for ($i=0; $i<$n; $i++){
for ($j=0; $j<$m; $j++){
$pair1 = [ $classA[$i], $classB[$j] ];
for ($z=0; $z<$n; $z++){
if($z != $i && $z != $j){
for ($y=0; $y<$m; $y++){
if($y != $i && $y != $j){
$pair2 = [ $classA[$z], $classB[$y] ];
$combinations[] = [$pair1, $pair2];
}
}
}
}
}
}
Apart from being inefficient, this is giving me many duplicates, is there a way to only get unique combinations?
I`d suggest to first create all the possible combinations, then for each pair , replace the row/column with null-s in "all possible combinations" , although it might not be the fastest, but it should work and give you the general idea
$allCombinations = Array();
foreach($classA as $value) {
$column = Array();
foreach($classB as $bPart) {
$column[] = Array($bPart,$value);
}
$allCombinations[] = $column;
}
$possibleCombinations = Array();
$sizeA = count($classA);
$sizeB = count($classB);
for($a = 0; $a < $sizeA; $a++) {
$column = Array();
for($b = 0; $b < $sizeB; $b++) {
$temp = $allCombinations;
for($i = 0;$i < $sizeA;$i++) {
$temp[$a][$i] = null;
}
for($i = 0;$i < $sizeB;$i++) {
$temp[$i][$b] = null;
}
// for $classA[$a] , $classB[$b] possible combinations are in temp now
$column[] = $temp;
}
$possibleCombinations[] = $column;
}
now , in $possibleCombinations you can see what are the possible combinations for given A/B indexes
In the first loop, it just creates all possible combination,
in the second loop, it will first get A and B value , copy all combinations array, then sets column A and row B values to null (because they can not be used, right?) , finally this possible combinations are stored in $temp and added to $possibleCombinations,
example:
$ab = Array($classA[$i],$classB[$j]);
$possibleCombinationsForAB = $possibleCombinations[$i,$j];
Build the cartesian product over both arrays without repeating points, remember array index. This does, however, not handle a same point present in both arrays.
$combinations = [];
$combined = [];
foreach ($classA as $keyA => $valueA) {
foreach ($classB as $keyB => $valueB) {
if (!isset($combined[$keyA][$keyB])) {
$combined[$keyA][$keyB] = $combined[$keyB][$keyA] = true;
$combinations[$keyA][$keyB] = [$valueA, $valueB];
}
}
}
var_dump($combinations);
If i understand correctly you want the following:
1. Choose a pair
2. Remove that pair's element's from your arrays
3. Courtesian product of the rest elements
Simplified code that does the above:
$classA = [ 1, 2, 3, 4 ];
$classB = [ 'a', 'b', 'c', 'd'];
function array_cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
$pair = [$classA[0], $classB[0]];
unset($classA[0]);
unset($classB[0]);
$pairs = array_cartesian($classA, $classB);
print_r($pairs);
The function is from this question.
Edit.
Output:
Array ( [0] => Array ( [0] => 2 [1] => b )
[1] => Array ( [0] => 2 [1] => c )
[2] => Array ( [0] => 2 [1] => d )
[3] => Array ( [0] => 3 [1] => b )
[4] => Array ( [0] => 3 [1] => c )
[5] => Array ( [0] => 3 [1] => d )
[6] => Array ( [0] => 4 [1] => b )
[7] => Array ( [0] => 4 [1] => c )
[8] => Array ( [0] => 4 [1] => d ) )
Plus the one you choose you have all the possible pairs as described in your tables.
Edit2.
foreach ($classA as $key1 => $value1) {
foreach ($classA as $key2 => $value2) {
$A = $classA; // Copying here otherwise your array will be empty
$B = $classB;
$pair = [$value1, $value2];
unset($A[$key1]);
unset($B[$key2]);
$pairs = array_cartesian($A, $B);
}
}

How to format following array in resultant array in php

I have following 2 arrays
$Name = Array
(
[0] => A
[1] => B
[2] => C
[3] => D
)
$zip = Array
(
[0] => 411023
[1] => 411045
[2] => 411051
[3] => 411023
)
Final array should be like this
$final = Array
(
411045 => B
411051 => C
411023 => A B
)
Hope you guys get it what i mean to say.
Here is another solution :
<?php
$Name = Array('A','B','C','D');
$zip = Array(411023,411045,411051,411023);
$namezip = array_combine($Name,$zip);
$res = array();
foreach($namezip as $nam=>$zp){
if(array_key_exists($zp,$res)){
$res[$zp] .= " ".$nam;
}
else{
$res[$zp] = $nam;
}
}
echo "<pre>";
print_r($res);
?>
$name = array ('A', 'B', 'C', 'D');
$zip = array (411023, 411045, 411051, 411023);
$final = array ();
for ($i = 0; $i < sizeof ($zip); $i++)
{
$n = $name [$i];
$z = $zip [$i];
if (!array_key_exists ($z, $final))
$final [$z] = array ();
$final [$z][] = $n;
}
print_r ($final);
You are looking for the second use case of phps array_keys() function where you can specify a value range. Using that you can simply iterate over the second array:
$final=array();
foreach ($zip as $key=>$anchor) {
if (! array_key_exists($final,$key))
$final[$key]=array();
$final[$key][]=array_keys($name,$anchor);
}
This generates a result $final where each element is an array again, most likely what you want. One could also interpret your question as if you ask for a space separated string, in that case just additionally convert the resulting array:
foreach ($final as $key=>$val)
$final[$key]=implode(' ',$val);

Categories