Solved

PHP - split and combine strings

Posted on 2014-11-27
4
98 Views
Last Modified: 2014-11-29
Hi,
What is the best way to combine the following values separated by a comma using a loop to check if a values exist?


from
       
       
       $itemPrice.1 = "40.00";
       $itemPrice.2 = "42.50";
       $itemPrice.3 = "56.40";
       $itemPrice.4 = "";
       $itemPrice.5 = "";
       $itemPrice.6 = "";
       $itemPrice.7 = "";
       $itemPrice.8 = "";
       $itemPrice.9 = "";
       
to  
       
       
       $itemPrice =  "40.00,42.50,56.40";
     


and a way to achieve the reverse,

from
       
       $itemPrice =  "3.20,2.50,6.40,5.80,17.60";
       
to      
       
       $itemPrice.1 = "3.20";
       $itemPrice.2 = "2.50";
       $itemPrice.3 = "6.40";
       $itemPrice.4 = "5.80";
       $itemPrice.5 = "17.60";
       $itemPrice.6 = "";
       $itemPrice.7 = "";
       $itemPrice.8 = "";
       $itemPrice.9 = "";

Thanks
0
Comment
Question by:sabecs
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 9

Expert Comment

by:Brian Tao
ID: 40468622

1.

If you can make them array elements rather than those not-so-common names, things will be much easier. You can then use implode and explode functions to do what you want to achieve.

2.

Are there always 9 items? or you can have any number of them?
0
 

Author Comment

by:sabecs
ID: 40468702
Yes, there won't be more than 9, are you saying I should make them as below?        
        $itemPrice[1] = "3.20";
        $itemPrice[2] = "2.50";
        $itemPrice[3] = "6.40";
        $itemPrice[4]= "5.80";
        $itemPrice[5]= "17.60";
        $itemPrice[6]= "";
        $itemPrice[7]= "";
0
 
LVL 9

Assisted Solution

by:Brian Tao
Brian Tao earned 200 total points
ID: 40468879
Correct.  Please see the sample code below:
function get_string_from_price($array_price){
  $ret = implode(",", $array_price);
  $ret = rtrim($ret, ",");
  return $ret;
}

function get_price_from_string($string_price){
  $tmp1 = array(1 => "", "", "", "", "", "", "", "", ""); // placeholders for 9 items, you don't need this, if you're going to discard the empty ones.
                                                          // the "1 =>" is to force the index to start at 1 to conform to your code, please note that in PHP array index starts at 0
  $tmp2 = explode(",", $string_price);  // create the array from the string
  array_unshift($tmp2, "");             // PHP array index starts at 0, so we need to unshift it with 1 element in the head
  $ret = array_replace($tmp1, array_slice($tmp2, 1, null, true)); // get the array elements starting from index 1 and replace the corresponding elements in the placeholder array $tmp1
  return $ret;
}

echo "<pre>\n";

$itemPrice_array1 = array(1 => "40.00", "42.50", "56.40", "", "", "", "", "", ""); // if you use array properly, I don't think you need the empty ones.
$itemPrice_string1 = get_string_from_price($itemPrice_array1);
echo "\$itemPrice_string1 is \"$itemPrice_string1\"\n";
/* output is:
$itemPrice_string1 is "40.00,42.50,56.40"
*/

$itemPrice_string2 = "3.20,2.50,6.40,5.80,17.60";
$itemPrice_array2 = get_price_from_string($itemPrice_string2);
echo "\n\$itemPrice_array2 is:\n";
print_r($itemPrice_array2);
/* output is:
$itemPrice_array2 is:
Array
(
    [1] => 3.20
    [2] => 2.50
    [3] => 6.40
    [4] => 5.80
    [5] => 17.60
    [6] => 
    [7] => 
    [8] => 
    [9] => 
)*/

echo "</pre>";

Open in new window

0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 300 total points
ID: 40469169
Arrays and strings are traditionally numbered starting with zero, not one.  If you're the only person who will ever see this code, you may be able to get away with numbered indexes that do not observe the standard practices, but if anyone else is going to see it, they are sure to be confused.

Typically arrays are processed with iterators.  These are programming concepts like while(), foreach(), etc., that allow you to think of the array as a single variable with any number of data elements, without having to impose artificial restrictions like "never more than 9."

Here is how I might do it.  Beware of loosely typed comparisons to NULL; if you want to preserve positions that contain zero values, you may need to rethink the design of some other parts of your application!

<?php // demo/temp_sabecs.php
error_reporting(E_ALL);

// COLLECT THE ITEM PRICES INTO AN ARRAY
$itemPrice[] = "3.20";
$itemPrice[] = "2.50";
$itemPrice[] = "6.40";
$itemPrice[] = "5.80";
$itemPrice[] = "17.60";

// NOT SURE WHY THESE NEED TO BE HERE?
$itemPrice[] = "";
$itemPrice[] = "";

// DISPOSE OF THE EMPTY POSITIONS
foreach ($itemPrice as $key => $val)
{
    if ($val == NULL) unset($itemPrice[$key]);
}

// COLLAPSE THE ARRAY INTO COMMA-SEPARATED VALUES
$str = implode(',', $itemPrice);
var_dump($str);

Open in new window

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PHP Mail error 3 43
Ajax and PHP 9 53
Why can I INSERT a DATETIME record into mysql but I can't UPDATE it? 15 37
How do I update select listbox after search 2 24
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question