0% found this document useful (0 votes)
76 views

Paypalphpcoding

PayPal Payment Gateway Integration in PHP provides a tutorial on integrating PayPal payments in a PHP application. It discusses: 1) How to integrate the PayPal payment gateway and process payments. 2) Using PayPal Instant Payment Notification (IPN) to update the database on payment status changes. 3) Testing the integration using PayPal's sandbox mode before going live.
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Paypalphpcoding

PayPal Payment Gateway Integration in PHP provides a tutorial on integrating PayPal payments in a PHP application. It discusses: 1) How to integrate the PayPal payment gateway and process payments. 2) Using PayPal Instant Payment Notification (IPN) to update the database on payment status changes. 3) Testing the integration using PayPal's sandbox mode before going live.
Copyright
© © All Rights Reserved
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 55

PayPal Payment Gateway Integration in PHP

Last modified on September 1st, 2020.

This tutorial will help you to integrate PayPal payment gateway using PHP with an example.

You will learn about three things today,

1. How to integrate PayPal payment gateway in your application and process payments.
2. What is PayPal IPN, why you should use it and an example implementation.
3. How to test PayPal payment gateway integration using PayPal sandbox.

PayPal provides different options to integrate the gateway like,

1. PayPal Payments Standard


2. Checkout
3. PayPal Commerce Platform
4. Recurring payments using PayPal Subscriptions
5. Payouts
6. Invoicing
7. Accept card payments
8. PayPal Pro

In this example, we will use “PayPal Payments Standard” method for integrating the paymen

What is inside?

1. How it works?
2. Payment gateway integration steps
3. File Structure
4. About PHP example to integrate payment using PayPal Payments Standard
5. Database Script
6. Go live
7. Payment gateway integration output

How it works?
PayPal payment gateway integration steps

1. Render PayPal payment form HTML with required parameters and “custom Pay Now butt
2. Set the suitable values for the form fields to fill up item information, merchant email id, ca
3. Set suitable form action with PayPal sandbox/live URL endpoint to which the payment de
4. Handle payment response in IPN listener to update database or to send email to the cust
5. Acknowledge user appropriately with the return/cancel page after payment cycle.

If you wish to process card payments refer the Stripe payment gateway integration using PHP articles.

File structure

Below screenshot shows the file structure of this PHP example code created for integrating P
The landing page shows an entry point for proceeding with the PayPal payment transaction

The return.php and the cancel.php files are the acknowledgement pages to which the user w

DBController.php file contains the code to create database connection object and to handle

About PHP example to integrate payment using PayPal Payments S

PayPal Payments Standard form HTML

In this HTML code we can see the PayPal Payments Standard form fields with a custom Pay

The PayPal payment form must contain the business email address, order information like it

By submitting this form, the payment parameters will be posted to the PayPal server. So, the

<body>
<div id="payment-box">
<img src="images/camera.jpg" />
<h4 class="txt-title">A6900 MirrorLess Camera</h4>
<div class="txt-price">$289.61</div>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr"
method="post" target="_top">
<input type='hidden' name='business'
value='PayPal Business Email'> <input type='hidden'
name='item_name' value='Camera'> <input type='hidden'
name='item_number' value='CAM#N1'> <input type='hidden'
name='amount' value='10'> <input type='hidden'
name='no_shipping' value='1'> <input type='hidden'
name='currency_code' value='USD'> <input type='hidden'
name='notify_url'
value='http://sitename/paypal-payment-gateway-integration-in-php/notify.php'>
<input type='hidden' name='cancel_return'
value='http://sitename/paypal-payment-gateway-integration-in-php/cancel.php'>
<input type='hidden' name='return'
value='http://sitename/paypal-payment-gateway-integration-in-php/return.php'>
<input type="hidden" name="cmd" value="_xclick"> <input
type="submit" name="pay_now" id="pay_now"
Value="Pay Now">
</form>
</div>
</body>

PayPal Notifications

PayPal provides  notifications using different mechanisms. It will be useful for updating your

1. Webhooks
2. IPN
3. PDT

Notifications should be used as part of the payment gateway integration process. Imagine y

You should not do this in the thank-you page. As there is no guarantee that this page will b

The dependable way of doing this is using PayPal notifications. You get a callback from PayP

What is PayPal IPN?

PayPal notifies the merchants about the events related to their transactions. This automatic

Notifications are done by PayPal on different type of events like, payments received, authori

An integral part of the payment gateway integration process in the ability to receive PayPal

The order fulfillment is an important step in a shopping cart software. It should be done via the PayPal notification and never s

Instant Payment Notification listener

The notify.php is created as the instant payment notification listener. This listener URL will be sent to PayPal via the form seen

This listener will be called asynchronously by PayPal to notify payment processing response
Below code verifies the payment status from the response returned by PayPal. If the paymen

<?php
// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory.
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation).
// Set this to 0 once you go live or don't require logging.
define("DEBUG", 1);
// Set to 0 once you're ready to go live
define("USE_SANDBOX", 1);
define("LOG_FILE", "ipn.log");
// Read POST data
// reading posted data directly from $_POST causes serialization
// issues with array data in POST. Reading raw POST data from input stream instead.
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode ('=', $keyval);
if (count($keyval) == 2)
$myPost[$keyval[0]] = urldecode($keyval[1]);
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
if(function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = urlencode(stripslashes($value));
} else {
$value = urlencode($value);
}
$req .= "&$key=$value";
}
// Post IPN data back to PayPal to validate the IPN data is genuine
// Without this step anyone can fake IPN data
if(USE_SANDBOX == true) {
$paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
$paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
return FALSE;
}
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
if(DEBUG == true) {
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}
// CONFIG: Optional proxy configuration
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
// Set TCP timeout to 30 seconds
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path
// of the certificate as shown below. Ensure the file is readable by the webserver.
// This is mandatory for some environments.
//$cert = __DIR__ . "./cacert.pem";
//curl_setopt($ch, CURLOPT_CAINFO, $cert);
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
{
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE)
}
curl_close($ch);
exit;
} else {
// Log the entire HTTP response if debug is switched on.
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." fo
error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
}
curl_close($ch);
}
// Inspect IPN validation result and act accordingly
// Split response headers and payload, a better way for strcmp
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));
if (strcmp ($res, "VERIFIED") == 0) {
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];

include("DBController.php");
$db = new DBController();

// check whether the payment_status is Completed


$isPaymentCompleted = false;
if($payment_status == "Completed") {
$isPaymentCompleted = true;
}
// check that txn_id has not been previously processed
$isUniqueTxnId = false;
$param_type="s";
$param_value_array = array($txn_id);
$result = $db->runQuery("SELECT * FROM payment WHERE txn_id = ?",$param_type,$param_value_array);
if(empty($result)) {
$isUniqueTxnId = true;
}
// check that receiver_email is your PayPal email
// check that payment_amount/payment_currency are correct
if($isPaymentCompleted) {
$param_type = "sssdss";
$param_value_array = array($item_number, $item_name, $payment_status, $payment_amount, $payment_currency, $txn_id);
$payment_id = $db->insert("INSERT INTO payment(item_number, item_name, payment_status, payment_amount, payment_curren

}
// process payment and mark item as paid.

if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
}
} else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation
// Add business logic here which deals with invalid IPN messages
if(DEBUG == true) {
error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
}
}
?>

DBController.php

This file handles database related functions using prepared statement with MySQLi. This is im

<?php

class DBController
{

private $host = "";

private $user = "";

private $password = "";

private $database = "";

private $conn;

function __construct()
{
$this->conn = $this->connectDB();
}

function connectDB()
{
$conn = mysqli_connect($this->host, $this->user, $this->password, $this->database);
return $conn;
}

function runQuery($query, $param_type, $param_value_array)


{
$sql = $this->conn->prepare($query);
$this->bindQueryParams($sql, $param_type, $param_value_array);
$sql->execute();
$result = $sql->get_result();

if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultset[] = $row;
}
}

if (! empty($resultset)) {
return $resultset;
}
}

function bindQueryParams($sql, $param_type, $param_value_array)


{
$param_value_reference[] = & $param_type;
for ($i = 0; $i < count($param_value_array); $i ++) {
$param_value_reference[] = & $param_value_array[$i];
}
call_user_func_array(array(
$sql,
'bind_param'
), $param_value_reference);
}

function insert($query, $param_type, $param_value_array)


{
$sql = $this->conn->prepare($query);
$this->bindQueryParams($sql, $param_type, $param_value_array);
$sql->execute();
}
}
?>

Database script

This section shows the payment database table structure in .sql format. This is provided with

--
-- Table structure for table `payment`
--

CREATE TABLE IF NOT EXISTS `payment` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`item_number` varchar(255) NOT NULL,
`item_name` varchar(255) NOT NULL,
`payment_status` varchar(255) NOT NULL,
`payment_amount` double(10,2) NOT NULL,
`payment_currency` varchar(255) NOT NULL,
`txn_id` varchar(255) NOT NULL,
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
);

How to test PayPal payment gateway integration using sandbox

Test! Test! Test! It is important. We are processing payments and you cannot be casual abou

PayPal provides excellent toolset to perform the end to end testing of the payment gateway

Testing the IPN is critical as it takes care of the order fulfilment process. Go through the belo

1. Sign Up with the PayPal developer account https://developer.paypal.com/


2. Create sandbox Business and Personal accounts via Dashboard -> Sandbox -> Accounts
3. Specify the sandbox business account email address in the payment form.
4. Add PayPal sandbox endpoint URL https://www.sandbox.paypal.com/cgi-bin/webscr to th
5. If you are using IPN, add sandbox URL to access via cURL.

Go live

Once everything is working good with the entire payment transaction processing flow, then

It requires to do the following changes in the code.

1. Replace the sandbox business account email with live email address.

<input type='hidden' name='business' value='PayPal Business Email'>


2. Change the PayPal Payments Standard form action URL as shown below.

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">

3. In notify.php, set the USE_SANDBOX constant to 0.

define("USE_SANDBOX", 1);

Payment gateway integration output

Below screenshot shows the product tile which includes PayPal payments standard form and

After successful payment transaction, the user will be automatically redirected to the return

The return url is nothing but a thank you page or order completion page. This is the last ste

An important thing to know is that the order fulfilment steps should not be done sequential
PHP with an example. I will walk you through a step by step process and make it easy for you do the

process payments.

ntegrating the payment gateway.


custom Pay Now button”.
, merchant email id, callback URLs.
which the payment details has to be posted on submit.
send email to the customer or both.
payment cycle.

eated for integrating Payment Gateway using PayPal Payments Standard method.
l payment transaction process. It will show a sample product tile containing PayPal payment fields fo

ges to which the user will be redirected appropriately. The notify.php is the IPN listener connect datab

n object and to handle queries on payment database update.

ayPal Payments Standard

ds with a custom Pay Now button. This example code targets the PayPal sandbox URL on the form ac

der information like item_number, name, amount, currency, and the callback and return page URLs.

e PayPal server. So, the user will be redirected to the PayPal Login and asked for payment confirmatio
eful for updating your backend processes, sending order notification and similar transactional jobs. F

on process. Imagine you are running a website that sells digital goods online. At the end of the paym

e that this page will be displayed in the user’s browser. There can be network failures, user’s might cl

et a callback from PayPal to your backend server (asynchronously) and you can manage the backend

ctions. This automatic callback can be used to perform administrative tasks and to fulfil orders. 

ments received, authorizations made, recurring payments, subscriptions, chargebacks, disputes, revers

ility to receive PayPal notification and process backend administrative processes.

PayPal notification and never should be done as part of the thank you or order completion page.

nt to PayPal via the form seen above. It can also be set in the PayPal REST API app settings. Paypal provides the  IPN listener code samples

t processing response. The payment response will be posted to this URL.


y PayPal. If the payment is verified and completed then the result will be updated in a database table
$ch) . PHP_EOL, 3, LOG_FILE);

URLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);


LOG_FILE);
yment_currency, $txn_id);
ayment_amount, payment_currency, txn_id) VALUES(?, ?, ?, ?, ?, ?)", $param_type, $param_value_array);
with MySQLi. This is important, always remember to use Prepared Statements as it will safeguard yo
t. This is provided with the downloadable source code with sql/payment.sql file. Import this file in you
using sandbox

cannot be casual about this implementation. Every bit of your PHP script should be tested thoroughl

the payment gateway integration. It provides a sandbox environment using which you can simulate

s. Go through the below steps to setup a PayPal Sandbox account and test you PHP code for payme

andbox -> Accounts.

m/cgi-bin/webscr to the payment form action.

processing flow, then it will be a time to go live with your PayPal payment gateway integration using
nts standard form and custom Pay Now button.

directed to the return URL as specified in the payment form. The return page will acknowledge the u

age. This is the last step in the payment gateway integration process.

ot be done sequentially in the return URL call. It should be done via the IPN callback or the other Pay
it easy for you do the integration.
yPal payment fields following by a Pay Now button.

listener connect database to save payment transaction response and data.

ox URL on the form action.

nd return page URLs.

r payment confirmation.
ar transactional jobs. Following are the different types of notifications provided by PayPal.

At the end of the payment process, you are obliged to send the digital product via email.

ailures, user’s might close the browser and there are so many variables involved in this.

manage the backend process from there.

to fulfil orders. 

backs, disputes, reversals and refunds.

the  IPN listener code samples for various languages.


ed in a database table.
as it will safeguard you from SQL injections and a primary step towards your security of the applicati
. Import this file in your test environment to run this example.
d be tested thoroughly before going live.

hich you can simulate the complete payment process including the payments and fulfillments step.

u PHP code for payment gateway integration.

eway integration using PHP code. Change the sandbox mode to live mode and do the following.
ill acknowledge the user as shown below.

llback or the other PayPal notifications.


by PayPal.

via email.
ecurity of the application.
nd fulfillments step.

do the following.
$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}

Alternative, Change to this:

<?php
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
$count = 0;

foreach($codes as $code) {
echo '<option value="' . $code . '">' . $names[count] . '</option>';
$count++;
}

?>

Share
Improve this answer
Follow
answered May 21 2018 at 5:12

Snowbases
2,11022 gold badges1818 silver badges2424 bronze badges
1
worked like a charm. Thanks for the answer :) 
– Utpal - Ur Best Pal
 Jul 13 2021 at 20:57
Add a comment
3
Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

becomes:

$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');

Share
Improve this answer
Follow
answered Dec 18 2010 at 23:45

Jakub
20.2k88 gold badges6363 silver badges9292 bronze badges
2
It's called an associative array, not a multidimensional array. 
– BoltClock
 Dec 18 2010 at 23:46
Add a comment
2
You can use array_merge to combine two arrays and then iterate over them.

$array1 = array("foo" => "bar");


$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);

Share
Improve this answer
Follow
answered May 17 2012 at 15:38

Haider Ali
84822 gold badges88 silver badges2525 bronze badges
Add a comment
2
All fully tested

3 ways to create a dynamic dropdown from an ar


This will create a dropdown menu from an array and automatically assign its respective value.

Method #1 (Normal Array)


<?php
$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');

echo '<select name="countries">';

foreach($names AS $let=>$word){
echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';

?>

Method #2 (Normal Array)


<select name="countries">

<?php

$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');


foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>

</select>

Method #3 (Associative Array)


<?php

$my_array = array(
'tn' => 'Tunisia',
'us' => 'United States',
'fr' => 'France'
);

echo '<select name="countries">';


echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>
Share
Improve this answer
Follow
edited Jun 20 2020 at 9:12

CommunityBot
111 silver badge
answered Aug 7 2013 at 7:50

Funk Forty Niner


74.2k1515 gold badges6464 silver badges132132 bronze badges
1
hm... downvote uncalled for. Downvoter, reason and care to elaborate? Obviously done "just cuz". Meh~ 
– Funk Forty Niner
 Nov 14 2013 at 19:55 
4
Aren't these all the same thing? I don't see any significant differences other than the names of the variables. 
– Patrick
 Apr 20 2017 at 9:21
Add a comment
2
Walk it out...

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

PHP 5.3+

array_walk($codes, function ($code,$key) use ($names) {


echo '<option value="' . $code . '">' . $names[$key] . '</option>';
});

Before PHP 5.3

array_walk($codes, function ($code,$key,$names){


echo '<option value="' . $code . '">' . $names[$key] . '</option>';
},$names);

or combine

array_walk(array_combine($codes,$names), function ($name,$code){


echo '<option value="' . $code . '">' . $name . '</option>';
})

in select

array_walk(array_combine($codes,$names), function ($name,$code){


@$opts = '<option value="' . $code . '">' . $name . '</option>';
})
echo "<select>$opts</select>";

demo
Share
Improve this answer
Follow
edited Mar 28 2014 at 1:30
answered Mar 25 2014 at 5:59

oLinkWebDevelopment
1,7411414 silver badges88 bronze badges
Add a comment
2
<?php

$codes = array ('tn','us','fr');


$names = array ('Tunisia','United States','France');

echo '<table>';

foreach(array_keys($codes) as $i) {

echo '<tr><td>';
echo ($i + 1);
echo '</td><td>';
echo $codes[$i];
echo '</td><td>';
echo $names[$i];
echo '</td></tr>';
}

echo '</table>';

?>
Share
Improve this answer
Follow
answered Sep 7 2015 at 2:19

r5d
57755 silver badges2424 bronze badges
Add a comment
2
foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a

while(($code = each($codes)) && ($name = each($names))) {


echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}

each() returns information about the current key and value of the array and increments the internal pointer by one
Share
Improve this answer
Follow
answered Jan 6 2017 at 18:53

PerceptorII
11911 gold badge11 silver badge55 bronze badges
Add a comment
2
Instead of foreach loop, try this (only when your arrays have same length).

$number = COUNT($_POST["codes "]);//count how many arrays available


if($number > 0)
{
for($i=0; $i<$number; $i++)//loop thru each arrays
{
$codes =$_POST['codes'][$i];
$names =$_POST['names'][$i];
//ur code in here
}
}

Share
Improve this answer
Follow
answered Mar 12 2017 at 14:45

fchan
2111 bronze badge
Add a comment
1
array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an at
Share
Improve this answer
Follow
edited Dec 21 2012 at 0:04

Dave Clemmer
3,7671212 gold badges4848 silver badges7272 bronze badges
answered Dec 20 2012 at 23:45

Calin Rusu
1111 bronze badge
Add a comment
1
I think that you can do something like:

$codes = array('tn','us','fr');

$names = array('Tunisia','United States','France');

foreach ($codes as $key => $code) {


echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}

It should also work for associative arrays.


Share
Improve this answer
Follow
answered Jul 7 2016 at 14:49

pashri
2133 bronze badges
Add a comment
1
I think the simplest way is just to use the for loop this way:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

for($i = 0; $i < sizeof($codes); $i++){


echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}

Share
Improve this answer
Follow
answered Jul 16 2016 at 8:13

SeReGa
88788 silver badges2626 bronze badges
Add a comment
0
if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}

if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}

foreach($doors as $a => $b){


Now you can use $a for each array....

$doors[$a]
$windows[$a]
....
}

Share
Improve this answer
Follow
answered Feb 7 2013 at 3:10

Gvice
38522 silver badges1010 bronze badges
Add a comment
0
I solved a problem like yours by this way:

foreach(array_keys($idarr) as $i) {
echo "Student ID: ".$idarr[$i]."<br />";
echo "Present: ".$presentarr[$i]."<br />";
echo "Reason: ".$reasonarr[$i]."<br />";
echo "Mark: ".$markarr[$i]."<br />";
}

Share
Improve this answer
Follow
answered Feb 19 2013 at 13:34

Ulugov
33733 silver badges99 bronze badges
Add a comment
0
You should try this for the putting 2 array in singlr foreach loop Suppose i have 2 Array 1.$item_nm 2.$item_qty

`<?php $i=1; ?>


<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>

@foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)


<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>

@endforeach `
Share
Improve this answer
Follow
answered Mar 2 2015 at 10:43

JADAV AKASH
922 bronze badges
Add a comment
0
Few arrays can also be iterated like this:

foreach($array1 as $key=>$val){ // Loop though one array


$val2 = $array2[$key]; // Get the values from the other arrays
$val3 = $array3[$key];
$result[] = array( //Save result in third array
'id' => $val,
'quant' => $val2,
'name' => $val3,
);
}

Share
Improve this answer
Follow
answered Oct 20 2015 at 8:27

Тарас Костюк
322 bronze badges
Add a comment
0
This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db

$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};

$k= (array)json_decode($answer);
$x =(array)json_decode($reason_id);
$number = COUNT(json_decode($reason_id, true));
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
$val = new ModelName();
$val->reason_id = $x[$i];
$val->answer =$k[$i];
$val->save();
}
}
Share
Improve this answer
Follow
answered Oct 30 2021 at 8:22

vivek raju
1
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how thi
– CommunityBot
 Oct 30 2021 at 11:32
Add a comment
-2
it works for me

$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

Share
Improve this answer
Follow
answered Jul 17 2013 at 16:44

mcjarod
1
Add a comment

Your Answer
$error3 = $_REQUEST['address'];
$error4 = $_REQUEST['email'];
re going about this wrong:

n from an array.
se the each() function in a while loop:
the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays

ultiple form inputs in an attempt to update products quantities in a shopping cart.


ay 1.$item_nm 2.$item_qty
h array in mysql db
elp others understand how this addresses the question asked. You can find more information on how to write good answers in the help center. 
endent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is
ers in the help center. 
hen one of the two arrays is finished.

You might also like