PHP objects and arrays - php

Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble
if the price of a book is less than $20.00 output the book’s name and price
if the book’s title comes after the letter R in the alphabet output the book’s title.
My code so far is:
<?php
class Book {
// Properties
public $price;
public $title;
// Methods
function set_price($price) {
$this->price = $price;
}
function get_price() {
return $this->price;
}
function set_title($title) {
$this->title = $title;
}
function get_title() {
return $this->title;
}
}
$first_book = new Book();
$first_book->set_price('$13.95');
$first_book->set_title('Moby Dick');
echo "Price: " . $first_book->get_price();
echo "<br>";
echo "Title: " . $first_book->get_title();
echo "<br>";
$second_book = new Book();
$second_book->set_price('$23.99');
$second_book->set_title('Wuthering Heights');
echo "Price: " . $second_book->get_price();
echo "<br>";
echo "Title: " . $second_book->get_title();
echo "<br>";
$book = array("Moby Dick", "Wuthering Heights");
echo "Book Titles: " . $book[0] . ", " . " and " . $book[1] . ".";
?>
Kind Regurds
Kelly

Seems like you got most of it already, for the rest I would add a function to your Book class to get the first character of the title, and then use the ord (PHP documentation here) to convert it to an integer so you can check if it comes after the letter R.
<?php
// Add this to your Book class to get the first character of the title so we can check
// if the book comes after the letter 'R'
public function get_first_char() {
$titleArray = str_split($this->title);
return reset($titleArray);
}
// Instantiate your books and set properties ...
// Loop over each book
foreach ($book as $bookItem) {
$price = $bookItem->price;
// Right now $price is a string ('$xx.xx'), we need it to be numeric
$price = (float) substr($price, 1);
if ($price < 20) {
echo $bookItem->title;
echo $bookItem->price;
}
// Use the ord function to convert the ascii character into an int
if (ord(strtoupper($bookItem->get_first_char())) > ord('R')) {
echo $bookItem->title;
}
}
?>

Related

PHP Call function from another function

Need to create function that will call other built-in and custom functions, problem is that each called function has different number of parameters.
I supply to a callerFunction required function name and required parameters in array, but how do i implement the actual function call?
P.S. I am aware of function scope, this is not a question now.
function myFunction(inputStr, paramOne, paramTwo) {
echo inputStr . " P1: " . paramOne . " P2: " . paramTwo;
}
function callerFunction(functName, functArgsArr) {
$myVar = "";
n = 1;
while n <= functArgsArr.length {
myVar = myVar . " " . functArgsArr[n];
n++;
}
%functName%("Hello World!", %myVar%);
}
callerFunction("myFunction", ["one", "two"]);
You could use the call_user_func_array PHP function:
<?php
function myFunction($inputStr, $paramOne, $paramTwo)
{
echo $inputStr . " P1: " . $paramOne . " P2: " . $paramTwo;
}
function callerFunction($functionName, array $functArgsArr)
{
// Prepends 'Hello World' to args array
array_unshift($functArgsArr, "Hello World");
// Calls $functionName passing the values of $functArgsArray as arguments
call_user_func_array($functionName, $functArgsArr);
}
callerFunction("myFunction", ["one", "two"]);
Working PHP Fiddle

How to echo/print within a fuction with undefined variables in php?

I am not the best at php but currently I am trying to learn. I can print fine outside of the function but the specific instructions I have been given require me to print the results within the function. I have tried
echo "$area";
echo "calculatearea ()";
ive searched but still cant figure out how to get a print within the function only outside of it.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
return $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
echo "Your rectangle circumference is: " . calculateCircumference() . '<br />' . "Your rectangle area is: " . calculateArea();
}
?>
<!---------------- Form---------------->
<div class="form">
<h3></h3>
<form action="PHP-sida4.php" method="POST">
<p>Length: <input type="text" name="Length"value=""></p>
<p>Width: <input type="text" name="Width"value=""></p>
<input type="submit" name="CalcBT" value="Calculate">
</form>
I need the return value of $area along with what I echo'd in the bottom to actually print within the first function ( calculateCircumference )
You can echo anything you want within the function but it won't show up until you call the function.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
// return $circ;
echo "Your rectangle circumference is: " . $circ . '<br />' . "Your rectangle area is: " . calculateArea();
return;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
calculateCircumference();
}
?>
I hope this helps!
Okay if am getting your question right, to need to return the area and some other text along with the area.
Let's begin with some house cleaning, therefore the $area global variable could be renamed to something else like $results Which will be an array or object. Taking it simple.
Lets go with an associative array where e.g:
$results = [
'area' => null,
'text' = null
];
From that your will be updating $results['area'] from the calculate function and also update the $results['text'] before calling echo, so probably extract the echoed text to another variable.
And now you can access $results anywhere within the file with both the area and the text:
To just be more expressive under CalculateArea() function do something like:
$results['area'] = $area;
Same thing with the echoed text.
You can use echo instead of return in your functions. To call them, your can just use function(); without any additional keyword :
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
echo $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
echo $area;
}
echo "Your rectangle circumference is: " ;
calculateCircumference() ;
echo '<br />' ;
echo "Your rectangle area is: " ;
calculateArea();
You can echo anything anywhere, be it inside a function or outside of it. If an echo is not performing, then there was either an error, or the line where the echo can be found was not executed.
In our case you have removed the echo after your functions, which, coincidentally happened to be the only place where they were called.

Replace first part of string with db string

Could u help me with code ?
I want to add t that script an option like :
when I type ex. data/pag , then script replaces data with key from mysql db and echo it like: replaced/pag . I mean it only replaces text before first and single "/".
Code :
$wyszukaj=$_GET['wyszukaj'];
$min_wartosc = 1;
if(strlen($wyszukaj)>=$min_wartosc)
{
$wyszukaj =htmlspecialchars($wyszukaj);
$zapytanie=$baza->prepare("SELECT * FROM wyszukiwarka WHERE nazwa LIKE :wyszukaj");
$zapytanie->bindValue('wyszukaj', $_GET['wyszukaj'],PDO::PARAM_STR);
$zapytanie->execute(array($wyszukaj));
if($zapytanie->rowCount()>0)
{
while($wynik=$zapytanie->fetch())
{
echo $wynik['nazwa'] . "<br>";
header('location:http://'.$wynik['login']);
}
}
else
{
echo "brak <b> " . $wyszukaj . " </b> w bazie danych ...";
}
}
else
{
echo "";
}

function only returns one value multiple times

I have this function:
function get_content($text_to_match) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
But when I call it like:
<div>
<?php
for ($i = 1; $i < count(get_content("text_to_match")); $i++) {
echo '<article>' .
'<h3>' . get_content("text_to_match")["string1"] . '</h3>'.
'<p>' . get_content("text_to_match")["string2"] . '</p>' .
'</article>';
}
?>
</div>
I only get the first match in the DB repeated as many times as the number of found items.
Where have I gone wrong?
use this code then fetch data properly
while($content = mysql_fetch_array($cont))
{
return $content;
}
Your logic is at fault. You are calling get_content function to get all matches for the loop, as well as to get individual elements out of the list. This is:
bad logic - the 2nd use case doesn't make sense
excessive - you shouldn't need to run a database query just to output an already retrieved result
What you probably want to do is:
foreach (get_content('text_to_match') as $content) {
echo '<article>';
echo '<h3>' . $content['string1'] . '</h3>';
echo '<p>' . $content['string2'] . '</p>';
echo '</article>';
}
With a few modifications in combination with tips from #Anant and #Unix One's answer, I arrived at this working solution:
Function definition
function get_content($text_to_match, $multiple=false) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if ($multiple) {
$content_array = [];
while($content = mysqli_fetch_array($cont)) {
$content_array[] = $content;
}
return $content_array;
} else {
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
}
Function calls
<?php
/* multiple items */
foreach(get_content("text_to_match", true) as $content) {
echo '<article>' .
'<h3>' . $content["string1"] . '</h3>' .
'<p>' . $content["string2"] . '</p>' .
'</article>';
}
?>
<?php
/* one item */
echo get_content("text_to_match")["string"];
?>

Get object class name from within parent class?

I am wanting to use the get_class($var) to show the class of an object. What would be the best way to do this? My code at the moment is:
abstract class userCharacter {
var $cName;
var $cLevel = 0;
var $cHP = 50;
var $cMP = 20;
function __construct($n) {
$this->cName = $n;
}
function showDetails() {
echo $this->cName . "<br />";
echo "Level: " . $this->cLevel . "<br />";
echo "HP: " . $this->cHP . "<br />";
echo "MP: " . $this->cMP . "<br />";
}
} // userCharacter
class warrior extends userCharacter {
} // warrior
And I create the object with:
$charOne = new warrior($name);
What I'm wanting to do is in the showDetails() function of the userCharacter class have a line similar to:
echo "Class: " . get_class($charOne) . "<br />";
But, I'm pretty sure that this won't work because the $charOne variable isn't in the right scope.
I'm thinking that I would need to declare $charOne with something like:
global $charOne = new warrior($name);
Would this work? If not, what is the best way to do this, if possible at all?
You want
echo get_class($this) ;
At runtime, the actual class will be figured out. That's what is cool about polymorphism.
However, even better, you want to do something like this:
echo $this->getClassDisplayName();
Then write that function for each subclass.
Or, the base class can have this type of function:
function getClassDisplayName()
{
return ($this->classDisplayName == "" ? getClass($this) : $this->classDisplayName );
}
Then in the constructor of your subclasses:
public __construct()
{
$this->classDisplayName = "The Mighty Warriors of Azgoth";
}

Categories