How to concatenate two arrays in PHP
I have two arrays of type A and Bed and .
A=[1,2,3,4] , B=[10,20,30,40]
I want to execute a mysql update query this way.
$abc1=mysql_query("update table set corr='1' WHERE id=10");
$abc1=mysql_query("update table set corr='2' WHERE id=20");
$abc1=mysql_query("update table set corr='3' WHERE id=30");
$abc1=mysql_query("update table set corr='4' WHERE id=40");
all this is the execution of the request in one go.
source to share
Using array_combine()
, you can create a new array, specify one array as keys and another as values โโin the new array. Then it's just a matter of looping through the resulting array and executing queries. Since you now have one array, use a loop foreach
and use keys (in this case all values โโfrom $a
) and values โโ(in this case all values โโfrom $b
) as values, re.
This assumes that the number of entries in both arrays is always the same. If they are not the same size it array_combine()
will return false - you can use this as a check before making requests.
$a = [1, 2, 3, 4];
$b = [10, 20, 30, 40];
$result = array_combine($a, $b);
foreach ($result as $k=>$v) {
mysql_query("UPDATE table SET corr='$k' WHERE id = '$v'");
}
That being said, this query is vulnerable to SQL injection and you should move to a new API that supports parameterized queries using placeholders ( mysqli_*
or PDOs). The API mysql_*
was deprecated in PHP 5.6 and removed completely in PHP7.
source to share