hello,

this my code how i can do it

$word = "a,b"; 

echo $first;  /// a
echo $second; /// b

thanks

Dani AI

Generated

Short answer: split the string on the comma, trim the pieces, and handle missing or extra pieces. and were on the right track splitting into parts, and ’s substr approach works only when positions are fixed. Below are two concise, more robust alternatives plus common pitfalls to watch for.

Use sscanf to grab everything before the first comma and everything after it (keeps spaces until you trim):

$input = "a, b";
$num = sscanf($input, "%[^,],%[^\n]", $first, $second);
$first  = isset($first)  ? trim($first)  : '';
$second = isset($second) ? trim($second) : '';
echo $first;
echo $second;

Use a regex split to tolerate optional spaces and limit to two parts (so extra commas stay in the second part):

$input = "a , b,rest,more";
$parts = preg_split('/\s*,\s*/', $input, 2);
$first  = isset($parts[0]) ? $parts[0] : '';
$second = isset($parts[1]) ? $parts[1] : '';
echo $first;
echo $second;

Troubleshooting & tips:

  • If values may contain commas or quotes, use PHP’s CSV parser (str_getcsv) instead of simple splitting.
  • Always trim() to remove stray whitespace and check existence before using indexes to avoid notices.
  • For HTML output escape values with htmlspecialchars() to avoid XSS.
  • The bug in ’s earlier snippet came from doing array($seatnumber) (that creates a single element) instead of splitting the string — make sure you actually split the string into parts.

These approaches keep parsing predictable and make it easy to handle missing or extra data cleanly.

Recommended Answers

All 7 Replies

or i want just print second value the B

thanks

or better store it in an array and then using key value echo it simple....try this out

here is the code

<?
$word = "a,b"; 
$word=explode(',',$word);

echo $word[0]; 
echo "<br>"; /// a
echo $word[1]; /// b
?>

try this

<?php
$str = 'a,b,c,d';

$a=(explode(',', $str));
echo $a[0]."<br/>";
echo $a[1]."<br/>";
echo $a[2]."<br/>";
echo $a[3]."<br/>";
?>

thanks

and what about this array

$seatnumber = "d,s";
$array = array($seatnumber);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "ticket: $array[$i]";

	echo "</br>";
}

is not work check it please .

thanks

$seatnumber = "d,s";
$array = explode(',',$seatnumber);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "ticket: $array[$i]";

	echo "</br>";
}

try this:

<?php
$word = "ab";
echo substr($word, 0,1); //prints a
echo "<br />";
echo substr($word, 1,1); //prints b
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.