This question already has answers here:
fastest way to find if all the elements of an array are distinct?
(4 answers)
Closed 6 years ago.
I have this array:
$number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
Now I want to get all unique values. Means the result should be:
$result = array("a", "b", "c");
Now I know that this can easily be solved with array_unique(). But I want to write my own little implementation of array_unique() just using a for loop, unset() and array_values().
Something like this maybe? Here we are looping through and array starting in one for from the position 0 and in the other from 1. We compare the $i position with all the others in array and if it finds two same it removes the second one.
<?php
$number = array("a", "b", "b", "c", "a", "b", "c", "b", "c");
$count = count($number);
for($i = 0; $i < $count; $i++) {
for($j = $i+1; $j < $count; $j++) {
if(isset($number[$j]) && isset($number[$i]) && $number[$i] == $number[$j]) {
unset($number[$j]);
}
}
}
print_r($number);
use array_unique()
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$unique_array=array_unique($number);
print_r($unique_array);
?>
//second posibility
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$unique_array=[];
foreach($number as $val)
{
$unique_array[$val]=$val;
}
print_r(array_values($unique_array));
?>
//Third posibility with for,unset,array_value
<?php
$number=array("a","b","b","c","a","b","c","b","c");
$count=count($number);
for($i=0;$i<$count;$i++)
{
if($i<count($number))
{
for($j=$i+1;$j<$count;$j++)
{
if($number[$i]==$number[$j])
{
unset($number[$j]);
}
}
}
}
$number=array_values($number);
print_r($number);
?>
expected result is
Array ( [0] => a [1] => b [2] => c )
Related
This question already has answers here:
variable variables
(5 answers)
Closed 3 years ago.
I have two arrays:
$my_array1= array("A", "B");
$my_array2= array("1", "2");
Is it possible to use variables ($x) in the index of the array like this:
for ($x = 1; $x <= 2; $x++) {
Echo $my_array.$x[0];
}
How to achieve this?
After referred in comment , i think it's work : here
$my_array1= array("A", "B");
$my_array2= array("1", "2");
and re-use your loop like:
for ($x = 1; $x <= 2; $x++) {
// to init the new name of array
$init = 'my_array'.$x;
// to use variable in the name of variable
Echo $$init[0];
}
I hope it's help you
I think what you're looking for is to be able to use key / value pairs.
You can do something like:
$array = array(
1 => "a",
2 => "b",
3 => "c",
4 => "d",
);
foreach ($array as $key => $value) {
echo "{$key} => {$value} ";
}
Or loop througout the numeric key values as you like.
How to extract only Numbers from an Array?
$myarray = array("A","B", "2","D");
I want to get numeric values ("2" in this example) from an array to a variable
You can use is-numeric and array-filter (PHP build-in functions):
$myarray = array("A", "B", "2", "D", "3");
$b = array_filter($myarray, "is_numeric");
Now $b is an array containing the strings: 2 and 3.
Edited Regarding your comment: if you have only 1 value and you want to add 10 to it you can do:
$myarray = array("A", "B", "2", "D");
$b = array_filter($myarray, "is_numeric");
$c = array_values($b); //reset the keys
$finalvalue = $c[0] + 10; // will output 12
<?php
$input = array('A','B', '2.2','D');
foreach($input as $v)
is_numeric($v) && $nums[] = $v;
// Take the first numeric found and add 10.
$result = isset($nums[0]) ? $nums[0] + 10 : null;
var_dump($result);
Output:
float(12.2)
This is the source of what i am trying to do:
source: a11993b18486c13240388
What i vae done so far:
$array = preg_split("/(,?\s+)|((?<=[a-z])(?=\d))|((?<=\d)(?=[a-z]))/i", $ref);
I am trying to convert the resulting $array into an object:
[
"a",
"11993",
"b",
"18486",
"c",
"13240388"
]
by grouping by 2 where first item is key and second is value:
Following is my desired outcome:
{
"a"=>"11993",
"b"=>"18486",
"c"=>"13240388"
}
Maybe there is even a better way to do that?
I would appreciate if someone kindly guide me about that.
You need to loop through array using for and in loop add values to new array.
$newArr = [];
for ($i=0; $i<count($arr); $i+=2)
$newArr[$arr[$i]] = $arr[$i+1];
Result
Array
(
[a] => 11993
[b] => 18486
[c] => 13240388
)
Check result in demo
Also if you want to do this using regex on string use
$ref = "a11993b18486c13240388";
preg_match_all("/([a-z])(\d+)/i", $ref, $matches);
$newArr = array_combine($matches[1], $matches[2]);
Check result in demo
try following :
$list = array(
"a",
"11993",
"b",
"18486",
"c",
"13240388"
);
$new_list = array();
for($i=0;$i<count($list);$i=$i+2) {
$new_list[$list[$i]] = $list[$i+1];
}
echo '<pre>'; print_r($new_list); echo '</pre>';
i hope answer to your question is this, because you are looking for object:-
$arr=[
"a",
"11993",
"b",
"18486",
"c",
"13240388"
];
$arrForObj = [];
for ($i=0; $i<count($arr); $i+=2){
$arrForObj[$arr[$i]] = $arr[$i+1];
}
$obj=(object)$arrForObj;
echo "<pre>";
var_dump($obj);
This question already has answers here:
Finding cartesian product with PHP associative arrays
(10 answers)
Closed 5 years ago.
i want combine 2 array like this
Example 1 :
Arr1 = ['A','B','C'],
Arr2 = ['D','E']
will be become
Arr3 = [
['A','D'],['A','E'],['B','D'],['B','E'],['',''] ....
]
Example 2 :
Arr1 = ['A','B','C'],
Arr2 = ['D','E']
Arr3 = ['G','H']
will be become
Arr4 = [
['A','D','G'],['A','E','G'],['','','']....
]
Any idea or suggest me algorithm can be like this thanks so much
Simplified version; merging array by index
$arr1 = range('a', 'b');
$arr2 = range('c', 'f');
$arr3 = range('g', 'k');
$arr4 = range('x', 'z');
$res = array();
// $counter = 1;
// while ($counter <= 4) {
// $array = "arr{$counter}";
// funcIndexMerge($res, $$array);
// $counter++;
// }
funcIndexMerge($res, $arr1);
funcIndexMerge($res, $arr2);
funcIndexMerge($res, $arr3);
funcIndexMerge($res, $arr4);
var_export($res);
function funcIndexMerge(&$res, $array) {
foreach ($array as $ari => $val) {
if (!isset($res[$ari])) {
$res[$ari] = array();
}
$res[$ari] = array_merge($res[$ari], array($val));
}
}
The problem you suggest is very similar to this Leetcode Challenge. The idea is to use Backtracking
Psuedo PsedoCode :
result := string Array
CartesianProduct(rowIndex, ArrayList, stringSoFar):
if rowIndex equal ArrayList.size:
Add stringSoFar to result
return
for(eachItem in ArrayList[rowIndex])
CartesianProduct(rowIndex +1 , ArrayList, stringSoFar + eachItem)
return
This is a workhorse which does all the computation and can be called like CartesianProduct(0, list of Array to be multiplied, "")
Suppose your ArrayList = [['A'], ['C', 'D']]. And CP be CartesianProduct
CP(0, AL, "")
(Take 'A')/
/
CP(1, AL, "A") (stringSoFar becomes 'A')
(Take C) / \(Take 'D'.Second Iteration with second array['C', 'D'])
/ \
CP(2, AL, "AC") CP(2, AL, "AD")
/ \
rowIndex equal size. rowIndex equals listSize i.e No more list to look
Add "AC" and return Add stringsoFar ("AD") to result and rerturn
My solution to the Leetcode problem(but in C++). Hopefully it'll give you some idea to write in PHP
class Solution {
public:
map<char, vector<string>> values {
{'2', vector<string>{"a", "b", "c"}},
{'3', vector<string>{"d", "e", "f"}},
{'4', vector<string>{"g", "h", "i"}},
{'5', vector<string>{"j", "k", "l"}},
{'6', vector<string>{"m", "n", "o"}},
{'7', vector<string>{"p", "q", "r", "s"}},
{'8', vector<string>{"t", "u", "v"}},
{'9', vector<string>{"w", "x", "y", "z"}}
};
vector<string> answer;
void doComb(int index, string digits, string sofar)
{
if(index == digits.size())
{
if(sofar != "")
{
answer.push_back(sofar);
}
return;
}
for(auto lett : values[digits[index]])
{
doComb(index + 1, digits, sofar + lett);
}
return;
}
vector<string> letterCombinations(string digits) {
doComb(0, digits, "");
return answer;
}
};
i am trying to compare two arrays using PHP. for example.
$one = ["A", "C", "B", "D", "A", so on....]
$two = ["A", "B", "B", "C", "A", so on....]
What I want to do is to compare the arrays and get the number of items that are the same. I only compare items with the same index. this is what i had in mind
$ctr=0;
if ($one[0] == $two[0]){
$ctr++;
}
if ($one[1] == $two[1]){
$ctr++;
}
// so on.......
echo $ctr++;
but the above code is only appropriate for fixed length of array. could anyone one help me with the code?
Take a look
$common = array_intersect($one,$two);
echo count($common);
// for key
$common = array_intersect_key($one,$two);
echo count($common);
First, you can use loop instead of writing manually every condition. Demo:
$ctr = 0;
for($i = 0; $i < count($one); $i++) {
$ctr += $one[$i] == $two[$i];
}
If you want to compare items with same index and length of array may differ, then,
$ctr = 0;
for($i = 0; $i < min(count($one), count($two)); $i ++) {
$ctr += $one[$i] == $two[$i];
}
In the second piece of code we check till the end of the shorter array.
If you are not interested in order, matching at any place would do, try array_intersect And for additional with index checking Array_intersect_assoc
You can use following to fulfill so:
$arr = array_intersect(array('a', 'b', 'c', 'd'),array('c', 'd', 'e', 'f'));
$array_length = sizeof($arr);
Hope this will help you.