Solved

PHP - split and combine strings

Posted on 2014-11-27
4
83 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
  • 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 108

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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

705 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now