array_combine wont work with duplicate value - php

I have two string :
$var1 = "1,2";
$var2 = "5,5";
I want output like:
5:1 5:2
I have tried explode() with array_combine() but it gives output like 5:2
My php code:
$res = array_combine(explode(',', $var2), explode(',', $var1));
foreach($res as $key=>$val) {
echo "$key:$val ";
}

Array keys must be unique and with your code you have two number 5, so you will get the second one. You could loop one array and access the other with the same key:
$array1 = explode(',', $var1);
$array2 = explode(',', $var2);
foreach($array2 as $key => $val) {
echo "$val:{$array1[$key]} ";
}

Related

Pass comma separated key string and get value of array according to key in PHP

I am trying to get value from array and pass only comma separated key string and get same output without. Is it possible without using foreach statement. Please suggest me.
<?php
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$valArr = array();
foreach($keyarray as $key){
$valArr[] = $array[$key];
}
echo $valStr = implode(",", $valArr);
?>
Output : apple,banana,orange
Use array_intersect_key
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
echo implode(",", array_intersect_key($array, array_flip($keyarray)));
https://3v4l.org/gmcON
One liner:
echo implode(",", array_intersect_key($array, array_flip(explode(",",$str))));
A mess to read but a comment above can explain what it does.
It means you don't need the $keyarray
Suggestion : Use separate row for each value, to better operation. Although you have created right code to get from Comma sparate key to Value from array, but If you need it without any loop, PHP has some inbuilt functions like array_insersect , array_flip to same output
$str = "1,2";
$arr1 = ["1"=>"test1","2"=>"test2","3"=>"test3"];
$arr2 = explode(",",$str);
echo implode(", ",array_flip(array_intersect(array_flip($arr1),$arr2)));
Live demo
you can try using array_filter:
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$filtered = array_filter($array, function($v,$k) use($keyarray){
return in_array($k, $keyarray);
},ARRAY_FILTER_USE_BOTH);
print_r($filtered);
OUTPUT
Array
(
[1] => apple
[2] => banana
[3] => orange
)
Another way could be using array_map():
echo $valStr = implode(",", array_map(function ($i) use ($array) { return $array[$i]; }, explode(",", $str)));
Read it from bottom to top:
echo $valStr = implode( // 3. glue values
",",
array_map( // 2. replace integers by fruits
function ($i) use ($array) {
return $array[$i];
},
explode(",", $str) // 1. Split values
)
);

How to split array in php with 2 strings?

How to split array with , in 2 parts so that that can be used as 2 strings in php?
I am getting this kind of array you can view image with this list.
I want to split this array to post id and title in separate columns.
<li id="recordsArray_'.$value['id'].','.$value['title'].'"></li>
Give a try with below code if it works for you
$arr = array('1,test1','2,test2','3,test3');
foreach($arr as $ar){
$res = explode(',', $ar);
$id = $res[0];
$title = $res[1];
echo 'id-'.$id;
echo ' title-'.$title;
echo '<br>';
}
If you want to separate array into two string, you can use explode like this short code:
$item = '4,test';
$var = explode(',', $item);
echo $var;
and for loop array, you can use
$array = array(YOUR_ARRAY);
foreach($array as $item){
$var = explode(',', $item);
echo $var;
}
Update 1:
You can use a simple array like below code:
$array = array(4, 'salar');
and use a code like this:
$array = array(4, 'salar');
foreach ($array as $item) {
dump(explode(',', $item));
}

How to check if Each value in $array1 the present in $array2 or not

I have known the cause of the problem, not in the code.
Content of the field at the base value of each line separately
So used str_replace to delete the line
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array1 = str_replace("\n","",$array1);
$array2 = explode(",",$query[filed2]);
$array2 = str_replace("\n","",$array2);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
I have a problem when I check if Each value in $array2 is present in $array1 or not
Table data:
filed1 | filed2
ahmed,jon,maya,omar | omar,maya
My code:
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array2 = explode(",",$query[filed2]);
$length = count($array1);
for ($i = 0; $i < $length; $i++)
{
if (in_array($array1[$i] , $array2))
{
//true
}else{
//false
}
}
or this:
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array2 = explode(",",$query[filed2]);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
My problem is my code doesn't work good, I am sure that my query gives the results and arrays too.
Output of array1:
Array ( [0] => maya [1] => omar [2] => ahmed [3] => join)
Output of array2:
Array ( [0] => omar [1] => maya )
So, where is the error in my code?!
Note :
I don't want check all value from array2 are in array1, I want check if Each value in $array2 is present in $array1 or not - focus on this word Each value not all value
Like:
if (in_array('omar',$array1))
{
echo 'found';
}else{
echo 'not found'; }
if (in_array('maya',$array1))
{
echo 'found';
}else{
echo 'not found';
}
if (in_array('jon',$array1))
{
echo 'found';
}else{
echo 'not found';
}
etc ...
But I do not want it this way, I want it inside a loop.
Yes you can use a loop in this case if you really want to, a simple foreach should suffice:
$array1 = array_map('trim', $array1); // on explode make sure remove trailing/leading spaces
$array2 = array_map('trim', $array2);
foreach($array1 as $name) { // so each value of array1
if(in_array($name, $array2)) { // is compared inside the contents of array2
// if found
echo "$name is found in " . '$array2';
} else {
echo "$name is NOT found in " . '$array2';
}
}
I think you should be iterating over array2 so all values of array2 are checked, not the other way around, because you said: "
check if Each value in $array2...
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query['filed1']);
$array2 = explode(",",$query['filed2']);
foreach($array2 as $value)
{
if (in_array($value,$array1))
{
//true
}else{
//false
}
}
I have known the cause of the problem, not in the code ...
Content of the field at the base value of each line separately
So used str_replace to delete the line
$query = $db->query_first("SELECT * FROM table ");
$array1 = explode(",",$query[filed1]);
$array1 = str_replace("\n","",$array1);
$array2 = explode(",",$query[filed2]);
$array2 = str_replace("\n","",$array2);
foreach($array1 as $value)
{
if (in_array($value,$array2))
{
//true
}else{
//false
}
}
array_diff() is a single function approach to getting an array of items not present in further arrays
$array1 = array('ahmed','jon','maya','omar');
$array2 = array('omar','maya');
$result = array_diff($array1,$array2); // Array ( [0] => ahmed [1] => jon )
you may need to switch parameter order to achieve your desired outcome.
you can also use array_intersect() to perform the reverse
#Ghost's solution produced the correct output, but as you state, you know the problem isn't your code. Apparently the problem is that the format of the data you are querying isn't quite matching. So, here is how you can approach debugging this problem:
var_dump() the data
The likely suspect is that some of the data have padding. (It's odd that #Ghost's suggestion of trimming the results didn't work.)
$array1 = explode(",",$query['filed1']);
$array2 = explode(",",$query['filed2']);
var_dump($array1);
echo "\n";
var_dump($array2);
echo "\n";
Inspect comparisons in the iteration
The above should reveal the problem. If not, you could take it a step deeper and see which exact comparison is failing in the in_array. If you don't have xdebug available, just loop within the loop:
foreach ($array1 as $value) {
if (in_array($value, $array2)) {
echo "\n[$value found in \$array2]\n";
} else {
echo "\n[$value NOT found in \$array2]\n";
}
foreach ($array2 as $value2) {
if ($value !== $value2) {
echo "\$array1's '$value' !== \$array2's '$value2'\n";
} else {
echo "\$array1's '$value' === \$array2's '$value2'\n";
}
}
}
The output will show you exactly what is wrong.
Note: You should include filed1 and filed2 in quotes since you are using them as string keys. When PHP parses your code, it will emit a notice (error) and fall back on interpreting it as a string.

Display array_key from PHP array?

Here I am Having an Issue:
I have two arrays like the following:
$array1 = array('1','2','1','3','1');
$array2 = array('1','2','3'); // Unique $array1 values
with array2 values i need all keys of an array1
Expected Output Is:
1 => 0,2,4
2 => 1
3 => 3
here it indicates array2 value =>array1 keys
Just use a loop:
$result = array();
foreach ($array1 as $index => $value) {
$result[$value][] = $index;
}
If you pass array_keys a 2nd parameter, it'll give you all the keys with that value.
So, just loop through $array2 and get the keys from $array1.
$result = array();
foreach($array2 as $val){
$result[$val] = array_keys($array1, $val);
}
The following code will do the job. It will create a result array in which the attribute val will contain the value that is searched in array and keys attribute will be an array that contains the found keys. Based on your values following is an example:
$array1 =array('1','2','1','3','1');
$array2 =array('1','2','3');
$results = array();
foreach ($array2 as $key2=>$val2) {
$result = array();
foreach ($array1 as $key1=>$val1 ) {
if ($val2 == $val1) {
array_push($result,$key1);
}
}
array_push($results,array("val"=>$val2,keys=>$result ));
}
echo json_encode($results);
The result will be:
[{"val":"1","keys":[0,2,4]},
{"val":"2","keys":[1]},
{"val":"3","keys":[3]}]

Compare two arrays and merging in PHP

I have two arrays:
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
Here $array1 has keys and values. Now I want to take the first value from $array1(as 1) and I want to check if this is repeated in this array .
Here 1 is repeated two times so I want to take the two keys 1,10 and display the corresponding values of these keys from $array2. If the value in $array1 is not repeated then I want to just display the value of this key from $array2.
I want to get the output as follows:
Hello Test
check
error
That means in $array1 1,10 keys have the same value so the value of 1 and the value of 10 from $array2 is merged then displayed.
Like 12 has 0 this is not repeated so simply take value of 12 from $array2.
Like 13.
How can I do this?
<?php
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$groupedKeys = array();
foreach($array1 as $key=>$arr){
$groupedKeys[$arr][] = $key;
}
foreach($groupedKeys as $key => $groupedKeyArr){
foreach($groupedKeyArr as $groupedKey){
echo $array2[$groupedKey];
}
echo "<br /> ";
}
?>
http://codepad.org/9R9s5lTM
There is a built in function that returns an array with the number of times a value is repeated http://php.net/manual/en/function.array-count-values.php
This is really rough, but a simple way of doing it could be:
<?
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$prev = $array1[1];
foreach($array1 as $key => $val)
{
if($val != $prev && $key != 1)
{
echo '<br />';
}
echo $array2[$key].' ';
$prev = $val;
}
?>
Example: http://codepad.org/OpLdtStp
This assumes that you're first key is always going to be 1 by the way.
I am providing you a function returns an array with the number of times a value is repeated in an array(as values) and values as the keys. Further task is not difficult.
function check_number_of_times_elements_occur_in_array($a)//returns values of array as keys, associating values being their total occurences in the array
{
$r=array();
foreach($a as $v)
++$r[$v];
return $r;
}
I think this will do for you..
function test($array1,$array2) {
$repeated_values = array_count_values($array1);
foreach($repeated_values as $key => $value){
if($value > 1) {
foreach($array1 as $key1 => $value1){
if($key == $value1){
$repeated_values_keys[] = $key1;
}
}
}
}
$str_top = "";
foreach($repeated_values_keys as $k){
$str_top .= $array2[$k]." ";
}
echo $str_top.'<br/>';
foreach($array2 as $key2 => $value){
if(!in_array($key2,$repeated_values_keys)){
echo $value.'<br/>';
}
}
}

Categories