Reputation: 2777
Question : How to display 15 random usernames with single quote on each username in an array?
Code :
$friendsArray = array("zac1987", "peter", "micellelimmeizheng1152013142",.....);
$randomfriends = array_rand($friendsArray, 15); //random select 15 usernames
foreach($randomfriends as $c => $friend){ //wrap each username in a single quote
$friendsArray[$c] = "'".mysql_real_escape_string($friendsArray[$c])."'";
}
$friendsArray2 = join(', ',$friendsArray);
echo $friendsArray2;
Output :
'hh', 'gg', 'ff', 'dd', 'ss', 'aa', 'oo', 'ii', 'uu', 'yy', 'tt', 'rr', 'ee', 'ww', 'qq', micellelimmeizheng1152013142, vv, bb
The problem can be seen obviously through the output. micellelimmeizheng1152013142, vv, bb are 16th, 17th and 18th entry without single quotes, they supposedly not to be shown, how to delete them?
Upvotes: 3
Views: 282
Reputation: 72991
Your issue is that you are not reseting $friendsArray
and merely overwriting certain keys with:
$friendsArray[$c] = "'".mysql_real_escape_string($friendsArray[$c])."'";
Here's your complete, corrected code, borrowing from zerkms:
shuffle($friendsArray);
$rand = array_slice($friendsArray, 0, 15);
foreach($rand as $friend) {
$sql_output[] = "'".mysql_real_escape_string($friend)."'";
}
$sql_output = join(', ',$sql_output);
Upvotes: 4
Reputation: 680
If you need to delete everything after the quoted strings, you can use this:
<?php
$sample = "'hh', 'gg', 'ff', 'dd', 'ss', 'aa', 'oo', 'ii', 'uu', 'yy', 'tt', 'rr', 'ee', 'ww', 'qq', micellelimmeizheng1152013142, vv, bb";
echo substr($sample, 0, strripos($sample, "'")+1)
Upvotes: 0
Reputation: 254926
shuffle($friendsArray);
$rand = array_slice($friendsArray, 0, 15);
And sample: http://ideone.com/hjrcY
Upvotes: 6