7

I want to output a specific value from array in php

Below is my code and array is $content

<?php
$content = $_POST;

for($i=1; $i < $content['itemCount'] + 1; $i++) {
  $name = 'item_name_'.$i;
  $quantity = 'item_quantity_'.$i;
  $price = 'item_price_'.$i;
  $image='item_image_'.$i;
  $option='item_options_'.$i;
  $total = $content[$quantity]*$content[$price];
}
?>

<?php
print_r( $content );

?>

Output is showing as below:

Array ( [currency] => INR 
[shipping] => 0 
[tax] => 0 
[taxRate] => 0 
[itemCount] => 3 
[item_name_1] => Our Nest 
[item_quantity_1] => 1 
[item_price_1] => 1900 
[item_options_1] => image: CF01108.jpg, productcode: 602793420 
[item_name_2] => Our Nest 
[item_quantity_2] => 1 
[item_price_2] => 2100 
[item_options_2] => image: CF01110.jpg, productcode: 123870196 
[item_name_3] => Our Nest 
[item_quantity_3] => 1 
[item_price_3] => 1800 
[item_options_3] => image: CF01106.jpg, productcode: 416267436 )

How to get productcode value in a php variable and echo it?

example:

602793420, 123870196, 416267436

4
  • You want all product code , in this array ? and what is you expected output ? Commented Dec 16, 2015 at 9:17
  • try it with echo substr($content[$option], strpos($content[$option], 'productcode:')+strlen('productcode:')); in your for loop Commented Dec 16, 2015 at 9:17
  • What is the data type of item_options_1 value? Commented Dec 16, 2015 at 9:17
  • The PHP language offers plenty of functions for string manipulation. Commented Dec 16, 2015 at 9:28

2 Answers 2

4

You can get the productcode using explode() function, like this,

$product_code = explode("productcode: ", $option)[1];

Here's the reference:

So your code should be like this:

<?php
    $content = $_POST;

    for($i=1; $i < $content['itemCount'] + 1; $i++) {
      $name = 'item_name_'.$i;
      $quantity = 'item_quantity_'.$i;
      $price = 'item_price_'.$i;
      $image='item_image_'.$i;
      $option='item_options_'.$i;
      $product_code = explode("productcode: ", $option)[1];
      $total = $content[$quantity]*$content[$price];
    }
?>
Sign up to request clarification or add additional context in comments.

2 Comments

i did't get exactly what i want, but explode() helped me. thank you. i got my answer $product_code = explode(", ", $content[$option]); did the work
@AseshaGeorge Glad it helped. :)
0

I would rather suggest this, in case the option of the item will have more values in future.

$option = "image: CF01110.jpg, productcode: 123870196";
$options = explode(",", $option);
echo $product_code = explode("productcode: ", $options[1])[1];

Thanks Amit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.