0

I have a database field named 'manufacturer' with some numbers separated by a pipe.

e.g 1572|906|1573

I would like to select the first number and store it as a variable.

This is my woeful effort that has yielded no success.

$thisproductmansarray=array(); //declare the array

$thisproductmans=$myfield["manufacturer"]; //For page title / breadcrumb etc
$xxarray=implode("|", $thisproductmans[$key]);
foreach($thisproductmans as $key=>$val){ 
$thisproductmansarray[]=$xxarray++;
echo $thisproductmansarray[0];
}

Could anybody give me a pointer. Thanks

1
  • 1
    Plenty of answers here, but here is another take on it...substr( $string, 0, strpos( $string, '|' ) ); Commented Dec 11, 2013 at 17:51

7 Answers 7

2
$xxarray=explode("|", $thisproductmans);
echo $xxarray[0]; // this should be what you want
Sign up to request clarification or add additional context in comments.

1 Comment

implode() is wrong in this case. it would be correct if the data is hold in an existing array.
2
$data = explode('|', $the-variable-where-the-data-is-in);
echo $data[0];

Will show the first number. In you example "1572".

Comments

1
$items = explode("|", $fieldfromdb);
$val = $items[0];

Comments

1
<?php
$str = '1572|906|1573';
$first_num = current(explode("|",$str));
echo $first_num;

Comments

0

Looks like explode is what you really want. explode() takes a delimited string and converts to an array of parts.

$thisproductmans=$myfield["manufacturer"]; //For page title / breadcrumb etc
$xxarray=explode("|", $thisproductmans[$key]);
if(count($xxarray) > 1)
    echo $xxarray[0];

Check out the man page for explode() if you need more info.

Comments

0

You can get the first number directly without using an array:-

$var = "1572|906|1573";
list($first) = explode('|', $var);

$first will now = 1572.

See it working and list().

If you have PHP V >= 5.4 you can do this:-

$var = "1572|906|1573";
$first = explode('|', $var)[0];
var_dump($first);

See it work.

Comments

-1

An example for you to use it in your code

<?php
$var = "1572|906|1573";

$array1 = explode("|", $var);

$first_value = $array1[0];
echo $first_value;  // Output here is 1572

?>

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.