-3

These are my possible strings.

$str = 'price-100-500';
$str = 'price-200-600';

I want two variables from the string. From first string, I want

$val1 = 100;
$val2 = 500;

From second string, I want

$val1 = 200;
$val2 = 600;

Please, how can I get?

5 Answers5

3

Use PHP explode function. See my codes as below:

$str = 'price-100-500';
$arr = explode('-',$str);
$val1 = $arr[1];
$val2 = $arr[2];
Nere
  • 4,097
  • 5
  • 31
  • 71
0

Just do in simple way:

$str = 'price-100-500';
list($val1, $val2) = explode('-', str_replace('price-', '', $str));
echo '<br>val1 : '.$val1;
echo '<br>val2 : '.$val2;

Output

val1 : 100
val2 : 500
Amit Rajput
  • 2,061
  • 1
  • 9
  • 27
0

Use

$str = 'price-100-500';
$exploded=explode("-",$str);
echo $exploded[1];//will echo 100
echo $exploded[2];//will echo 500

Similarly you can explode any string

Gaurav Rai
  • 900
  • 10
  • 23
0

Assuming that you are willing to have this from several similar $str, and if you have them as an array, you can use the following code block to get them all as array output --

foreach($strings as $string){
    $arr = explode('-',$string);
    $result[$string]['val1'] = $arr[1];
    $result[$string]['val2'] = $arr[2];
}

print_r($result);

This will give you an output like

Array
(
    [price-100-500] => Array
        (
            [val1] => 100
            [val2] => 500
        )

    [price-200-600] => Array
        (
            [val1] => 200
            [val2] => 600
        )

)

For better and exact answer you should provide better explanation of your problem. Hope for the best.

Thanks...:)

masud_moni
  • 1,121
  • 16
  • 33
0

For your first example:

 <?php

        $str = 'price-100-500';
        $arrayStr=explode("-",$str);
        $val1 = $arrayStr[1];
        $val2 = $arrayStr[2];

    ?>

If u wan't a function you can use this:

<?php

    $str = 'price-100-500';
    $array = getMyVar($str);
    echo $array[0];
    echo $array[1];


    function getMyVar($str){
        $arrayStr=explode("-",$str);
        $val1 = $arrayStr[1];
        $val2 = $arrayStr[2];

        return array($val1,$val2);
    }

?>
rdn87
  • 739
  • 5
  • 18