Why the output is not a string - php

I tried many time, but I still don't understand why the output is not a string, anything wrong ? help me check it. The final output should be a uppercase name string
<html>
<p>
<?php
// Create an array and push on the names
// of your closest family and friends
$name = array();
array_push($name,"Mike");
array_push($name,"Jane");
array_push($name,"Jack");
array_push($name,"Nike");
array_push($name,"Ash");
array_push($name,"Chris");
array_push($name,"Zark");
// Sort the list
sort($name);
join(",",$name);
// Randomly select a winner!
$random = count($name,rand(0,7));
// Print the winner's name in ALL CAPS
$winner = strtoupper($random);
print($winner);
?>
</p>
</html>

$random = count($name,rand(0,7));
This line assigns the count of elements in $name. I don't know what else you expected to get back other than a number here.
What you really want:
echo strtoupper($name[array_rand($name)]);
http://php.net/manual/en/function.array-rand.php
Other Notes:
Your call to join() doesn't do anything useful since you're not doing anything with the return value.
Your call to sort is pointless if you're just picking a random entry later.
Pick a plural name for your array names so you know they are arrays. $names instead of $name.
If you know all of the array elements ahead of time, no need for array_push(), just use an array literal: array('Mike', 'Jane', /* etc */)
If you're outputting data into the context of HTML, always use htmlspecialchars() to make sure any reserved characters are escaped properly. This isn't a problem with the code you literally have here, but will be as soon as you want to output < or ".

Related

Search for all elements in a PHP array

With the updated code below, my search is working, but only using the last word in the Array. Is there a way to search the MySQL column using all words the user inputted?
Note: All input sanitization and escaping is completed in my code but not shown here.
I have two PHP arrays: $search_exploded (user inputted search terms) and $metaphoneArr (metaphones of keywords in MySQL).
I'm cycling through $search_exploded and $metaphoneArr, and if the Levenshtein is less than 2, then I'm adding the metaphone element to a third array called $levenResultsArr.
In MySQL, I'm joining two tables, and if there's a result in my third array ($levenResultsArr) that matches a row in my metaphone_col, then I want the results printed. Somehow, though, I am not referencing the third array correctly in the MySQL statement.
Any advice? Here is part of my PHP code.
$levenResultsArr = array();
foreach ($search_exploded as $search_each => $searchWord) {
$search_each2 = metaphone($searchWord);
echo $search_each2 . "<br/>";
foreach ($metaphoneArr as $metaword => $val) {
$lev = levenshtein($search_each2, $val);
if ($lev < 2) {
array_push($levenResultsArr, $search_each2);
}
}
}
// And shown below is the MySQL statement
$constructs = "
SELECT vt.idvideolist,
vt.videotitle,
vt.videodescription
FROM videolist_tbl vt
INNER JOIN keyword__video k2v ON (vt.idvideolist = k2v.video_id)
INNER JOIN keywords_tbl k ON (k2v.keyword_id = k.idkeywords_tbl)
WHERE k.metaphone_col = '$search_each2'
";
It's only searching using the last word in the array instead of all words in the array.
You're correct that you aren't referencing your array correctly in your query. You are simply referencing the variable '$search_each2'. You want to check the entire array. The best way to do this would to be to convert the array to a string using implode and using the MySQL IN clause. We need to modify the array first to format it correctly:
foreach($levenResultsArr as &$foo){
$foo = "'".$foo."'"; //add single quotes around each object in the array
}
$levenAsStr = implode(",", $levenResultsArr);
Then simply change your last line to the following:
WHERE k.metaphone_col IN (".$levenAsStr.")";
Did this from memory because I'm not in a testing environment, please let me know if there are any syntax errors. Should work for you!
Without seeing more of the code its a bit difficult to determine what is going on. A couple of thoughts though.
What var is the array containing all search terms?
I noticed you are pushing items into $levenResultsArr. I don't see it being used in the query though.
If it is $search_each_2 you may try using the IN syntax:
WHERE k.metaphone_col IN '$search_each2';
This will only match exact values however. i.e.:
some value does not return if the IN array contains value. The array would have to contain some value
If you need it to match partial searches you may try using LIKE with wildcards: %
WHERE k.metaphone_col LIKE "%searchTerm1%"
OR k.metaphone_col LIKE "%searchTerm2%"
OR k.metaphone_col LIKE "%searchTerm3%"
You could potentially use the implode function to create the sql string from the array: http://php.net/manual/en/function.implode.php

What is the purpose of associative array

I am new to this array in forms. I tried to get rid of the associative array in this line
("F001"=>"a","F002"=>"b","F003"=>"c","F004"=>"d","F005"=>"e","F006"=>"f","F007"=>"g","F008"=>"h","F009"=>"i","F010"=>"j")
and made it ("F001", "F002" and so on) but program wont work. If I put it back it will work. My question is why it wont work if i get rid of the associative array?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['search'])) {
// move $students into the if statement cause we won't
// need it unless they're searching
$students = array (
array ("F001"=>"a","F002"=>"b","F003"=>"c","F004"=>"d","F005"=>"e","F006"=>"f","F007"=>"g","F008"=>"h","F009"=>"i","F010"=>"j"),
array ("albert","berto","charlie","david","earl","francis","garry","harry","irish","james"),
array (1,2,3,3,2,1,2,1,3,1)
);
$idNumber = $_POST['search'];
// we can use isset here because the student id *is* the key.
// if it was the value, than we would use array_search() and
// check if it returned false
if (isset($students[0][$idNumber])) {
// array_keys returns the keys of an array as an array,
// allowing us to find the numerical index of the key
$studentIndex = array_search($idNumber,array_keys($students[0]));
// printf basically allows for formatted echoing. %s means
// a string. %d means a number. You then pass in your
printf('Student ID: %s<br>Name: %s<br>Grade: %d', $idNumber, $students[1][$studentIndex], $students[2][$studentIndex]);
}
else {
// use htmlspecialchars() to encode any html special characters cause never trust the user
printf('No student with ID "%s" found.', htmlspecialchars($idNumber));
}
}
?>
<form action="" method="POST">
Id number: <input type="text" name="search">
<input type="submit" value="search">
</form>
</body>
</html>
Why it doesn't work if you remove it is mentioned in the comments:
// we can use isset here because the student id *is* the key.
// if it was the value, than we would use array_search() and
// check if it returned false
The reason behind that decision isn't clear from the example, but the letters those keys represent could have a wider meaning to a bigger system, and therefore a decision was taken to make it associative.
As for the purpose of an associative array, it can make searching for specific items simpler, especially in multi-dimensional arrays. It also can improve readability.
Trying to understand the following would be a pain at best:
$posts[0][1][0][7][4] = 'value';
Where as understanding the below is a little easier:
$posts[newest][1][information][tags][4] = 'value';
The use of associative arrays above make it easier to see that in an array of posts, the newest post with index 1 has information, and the 5th tag (because of 0 indexing) is 'value'.

Picking a random string from an array

Trying to get this code to work. It might be easier to show what I'm trying to do, and what is missing:
<?php
$array=array(
"something",
"something else"
);
/*pick a random entry in the array and store it as $output*/;
if(strpos($output,"else") !== false){
//do stuff;
}
echo "<div>";
echo $output
echo "</div>"
?>
As you can see, I'm having trouble trying to store a random entry in $output. What I want to do is to pick a random entry from the array, run a strpos on the result to do additional things if the conditions are met, and then output the same random entry between the divs.
EDIT: In case it's not clear, the line commented with /* and */ is supposed to be a 'fill in the blank' line, and not a 'this comment refers to the lines of code below' comment.
Use array_rand() to get a random entry.
$output = $array[array_rand($array)];
Generate a random number between zero and one less than the length of the array, use that as the array index to get a random item from the array.
<?php
$output = $array[rand(0, count($array)-1];

Returning string value in php array

Its a simple problem but i dont remember how to solve it
i have this array:
$this->name = array('Daniel','Leinad','Leonard');
So i make a foreach on it, to return an array
foreach ($this->name as $names){
echo $names[0];
}
It returns
DLL
It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'
try this one :
foreach ($this->name as $names){
echo $names; //Daniel in first iteration
// echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'
}
echo $this->name[0];// gives only 'Daniel' which is the first value of array
Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].
Edit: Maybe it makes sense to use more descriptive names for your variables.
For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.
Additional answer concerning your results :
You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.
Use your iterative element to get the complete string everytime, the alias you created after as.
If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :
http://php.net/manual/fr/control-structures.foreach.php
http://us1.php.net/manual/fr/language.types.array.php

PHP Calculation in variables from foreach output

I have this code:
$fookerdos = '';
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos .= file_get_contents($someposoA);
//to print them i you want
print $fookerdos;
So my problem that for this code will outputs many numbers becouse of many files.
for example will out output this
3.5 -6.7 6.68 -0.2 and so on..
now i want all this numbers to make them (addition)
i know how to addition some 2-3 variables, but i additions many numbers that I even dont know how many they are.
for example
print "3.5 + "-6.7" "6.68" "-0.2";
Thx :)
Does each file contain only a single number, or can they have more than one numbers?
From your previous edits, it seems as if one file contain only a number.
In that case, you can store the values in an array and sum the numbers using array_sum() or perform any other calculation as needed.
Here is a sample code for you:
$fookerdos = array ();
foreach (glob("records/*/*/kerdos.txt") as $somekerdos) {
$fookerdos[] = file_get_contents($somekerdos);
}
echo array_sum ($fookerdos);

Categories