tags:

views:

57

answers:

2

Hi,

Hope you are fine. My question :

In MYSQL i have a table with this type of field

Field Name: TAGS Value : xavier,celine,marise,leon,john,cathy,polux,maurice


In PHP i do this

$xwords = array();
function array_rpush(&$arr, $item)
{
  $arr = array_pad($arr, -(count($arr) + 1), $item);
}

$tags = requete("SELECT tags FROM tbl_tags LIMIT 1;");
while($dtags = mysql_fetch_assoc($tags)){
  $words .= array_rpush($xwords, $dtags['tags']);
}

// MY ARRAY XWORDS FOR DEBUG
//
// Array ( [0] => xavier, celine, marise, leon, john, cathy, polux, maurice
//

My script need to find the first letter of each word in this list and check if he match with A / B / C (i create an A-Z index page)

// COUNT $XWORDS VALUE
$total = count($xwords);
// total =1
for($i=0; $i < $total; $i++)
{
 $wtags = explode(",",$xwords[$i]);
 // wtags = Array ( [0] => xavier [1] => celine [2] => marise... )
  while (list($idx,$val) = each($wtags)) {
    echo $val{0}."<br>";
    echo substr($val,0,1)."<br>";
  }
}

echo $val{0}."<br>"; OR echo substr($val,0,1)."<br>" give me just x and nothing after (while give me only the first letter for the first record in array... amazing :))

Perhaps you can help me find a solution. Thanks

A: 
$sum = array();
foreach($wtags as $tag){
  $tag = trim($tag);
  empty($sum[$tag{0}])  ?    // if we don't have a $sum element for this letter
              $sum[$tag{0}] = 1  :    // we initialize it
              $sum[$tag{0}]++;        // else, we sum 1 element to the count.
  //$tag{0} is the first letter.
}

// the array $sum has the total of tags under each letter
//
// $sum[x] = 1
// $sum[c] = 2
// $sum[m] = 2
// $sum[l] = 1
// $sum[j] = 1
// $sum[p] = 1
Sebastián Grignoli
What does that curly brace syntax mean?
Peter Ajtai
It means "the character at position 0 of this string"
Sebastián Grignoli
Thanks... so in cases where `x[i]` could be misinterpreted as an array element, you can use `x{i}`.
Peter Ajtai
When you use $variable[2] you are always refering to the element under key 2 of an array called $variable.When you use $variable{2} you are refering to the 3rd character of the string called $variable.
Sebastián Grignoli
@Sebastian - Yeah. But when $variable is a string, $variable[2] will show the 3rd character.... Thanks. Wasn't familiar w the curly bracket notation.
Peter Ajtai
+2  A: 

The problem with your code is that it generates:

Array ( [0] => "xavier" [1] => " celine" [2] => " marise"... )

So $val[0] = " ". Try to trim($val):

$val = trim($val);
print $val[0];
Paulo Scardine
Good catch, +1.
Sebastián Grignoli