Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
How to relate two arrays in PHP

I have two arrays like A & B.


A=[1,2,3,4] , B=[10,20,30,40]

I want to execute a mysql update query in a way like this.


$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 these query execution in one go.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Just loop and use the index for the second array

 $as=[1,2,3,4] , $bs=[10,20,30,40]; foreach ($as as $key=>$val) { $abc1=mysqli_query("update table set corr='".$val."' WHERE id=".$bs[$key]); }

Note: you should not use mysql , use mysqli instead

Note: always escape

about 4 years ago · Santiago Trujillo Report

0

Using array_combine() , you can create a new array, specify one array as keys and the other 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 an array, use a foreach loop and use the keys (in this case all the values of $a ) and the values (in this case all the values of $b ) as the values you are setting.

This assumes that the number of entries in both arrays is always the same. If they are not the same size, array_combine() will return false; you can use it as verification before doing the queries.

 $a = [1, 2, 3, 4]; $b = [10, 20, 30, 40]; $result = array_combine($a, $b); foreach ($result as $k=>$v) { mysqli_query("UPDATE table SET corr='$k' WHERE id = '$v'"); }

That said, this query is vulnerable to SQL injection and you should upgrade to a newer API that supports parameterized queries with placeholders ( mysqli_* or PDO). The mysql_* API was deprecated in PHP 5.6 and completely removed in PHP7.

  • Why shouldn't I use mysql_* functions in PHP?

  • How can I prevent SQL injection in PHP?

  • Handbook for array_combine()

about 4 years ago · Santiago Trujillo Report

0

$a=[1,2,3,4];$b=[10,20,30,40];
$res=array_combine($a, $b );
foreach ($res as $key => $value) {
    $abc1=mysql_query("update table set corr='".$key."' WHERE id=".$value);
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!