Functions Part.1 函式1

Functions Part.1 函式1

Introducing Functions 介紹函式


Functions are reusable pieces of code that you can use throughout an application, saving you lots of copying and pasting.
函式為可在整個應用程式裡頭重複利用的程式區塊,從而節省你大量的剪貼作業。

PHP has lots of built-in functions, and we'll learn some of them in these exercises. The first set of functions we'll learn about are string manipulation functions.
PHP有很多的內建函式,而我們將在這一次的課程裡頭學到一部分。首先我們會學到的程式庫是字串處理相關的函式。

strlen() is one of the most common String functions in PHP. You pass it a string, or variable containing a string, and it returns the number of characters in that string. An example might be:
strlen()是PHP函式中最常用的一個。你傳入一個字串,或者是一個存放字串的變數,函式則會回傳該字串總共有多少個字元(例如:goblinlab會回傳9)。以下有個例子:


// get the length of a string and
// print it to the screen
  $length = strlen("david");
  print $length;

Instructions 操作指引

Use the index.php tab to write your own code.
使用 index.php 來撰寫你的程式碼

Get the length of your own name, as I did for mine, and print it to the screen.
取得你英文名字的長度,就像是我取得自己的一般,並將它印在畫面上。


String Functions I 字串函式1


Another very common string function is substr(). This function allows you to return a substring (piece of) of your string.
另一個非常常用的字串函式為 subset() 。這個函式能讓你回傳此字串的部分字串。(例如:能讓你從goblinlab取出goblin的意思)

You pass this function the string you want to get a substring of, the character in your string to start at, and how many characters you want after your starting point. An example might be:
你傳到函式裡頭的參數包含了有:想要取得部分字串之字串,該部分字串的起始索引,想取得部分字串的長度。以下有個例子:



$myname = "David";

// you can manipulate strings easily
// with built-in funtions too
$partial = substr($myname, 0, 3);
print $partial;
// prints "dav"

NOTE: the second parameter (the starting character) is based on a zero-indexed array (i.e. the first character in your string is number 0, not number 1).
提示:第二個參數(該部分字串的起始索引)是基於零索引陣列,易言之你字串的起始字元索引值是由0算起而非1。

Two other very useful string functions are strtoupper() and strtolower(), which make your entire string UPPERCASE or lowercase. Here is an example of each:
另外還有兩個有用的字串函式為strtoupper()strtolower(),能協助將字串轉成全大寫字串或全小寫字串。以下有相關的例子:


$uppercase = strtoupper($myname);
print $uppercase;
// prints "DAVID"

$lowercase = strtolower($uppercase);
print $lowercase;
// prints "david"

You can also call these functions on a string directly, like so:
你也能夠呼叫這些函式透過直接傳入字串,像這樣:



print strtolower("David");
// prints "david"

Instructions 操作指引

Use the index.php tab to write your own code.
使用 index.php 來撰寫你的程式碼

Get a partial string from within your own name and print it to the screen. Then try making your name upper case and lower case and print those to the screen as well.
從你的名字裡頭取出部分字串並印在畫面上。然後試著將你的名字轉成全大寫和全小寫,然後一併印在畫面上。


String Functions II 字串函式2


strpos() find the position of the first occurrence of a substring in a string.
strpos()能找到字串裡某部分字串的起始字元索引值。



strpos("emily", "e"); // 0
strpos("emily", "i"); // 2
strpos("emily", "ily"); // 2
strpos("emily", "zxc"); // false

The parameters passed to strpos() are the haystack and the needle. The function tries to find the needle in the haystack.
要傳入函式的參數有兩個,分別是要檢查的字串以及要尋找的部分字串。你可以理解成第一個參數為大海,第二個參數為針,該函式試著要在大海裡撈針。

It returns either the index of the first character, or false if the needle cannot be found.
如果找到了,該函式會回傳該部分字串的起始字串索引值。找不到的話就回傳false



if (strpos("david","h") === false) {
  print "Sorry, no 'h' in 'david'";
}
// prints the "Sorry" message

Use the editor to create your own haystackand needle combinations. You can use variables for both haystack and needle.
使用編輯器來建立你要檢查的字串以及要尋找的部分字串。你可以將這兩個資料存在變數裡頭。


Instructions 操作指引

- On line 6, use strpos() passing in your name as the haystack and a letter from your name as the needle.
- 在第6行,使用strpos()傳入你的名字作為要檢查的字串,並選擇其中一個字元作為要尋找的部分字串。
- On line 13, test if strpos() === falsewhere the needle is not in the haystack. Print out an error message inside your if block.
- 在第13行,測試if strips() === false 來監控在要檢查字串裡頭找不到所要找尋部分字串的情況。在if條件式的實作區塊裡印出錯誤訊息。


Math Functions I 數學函式1


Let's move on to a bit of arithmetic. The most common Math function you'll use is round(). This function rounds floating point numbers (numbers with decimal points in them) up or down.
接下來讓我們作一點運算吧。最常用的數學函式就是round()。此函式能將某個浮點數進行四捨五入運算,甚至是可取到指定的位數。

You can use round() to round your number to an integer, or to round off complex floating point numbers to a specific number of decimal places. This is accomplished by passing a second, optional parameter to round(), telling it how many decimal places you want the number rounded to.
你能夠使用round()來將浮點數四捨五入後變成一個整數。或者是將一個複雜的浮點數四捨五入取到指定的位數。(例如3.1415926取到3.14),要做到這樣還要多傳入一個非必填參數到round()裡頭,告訴它你想要取小數到第幾位。

Here's an example:
這裡有一個例子:



// Round pi down from 3.1416...
$round = round(M_PI);
print $round; // prints 3

// This time, round pi to 4 places
$round_decimal = round(M_PI, 4);
print $round_decimal; // prints 3.1416

NOTE: M_PI is a PHP constant that is equal to pi.
提示:M_PI是一個PHP常數(內建,不會改變的數),其值等於圓周率pi。


Instructions 操作指引

Use the exercise window to try rounding some numbers for yourself. You can use M_PIif you like; it's my favorite floating point number.
使用練習視窗來試著將一些浮點數進行四捨五入。你能夠使用M_PI假如你想要的話;那是我個人非常喜歡的浮點數。


Math Functions II 數學函式2


A very common and useful function is rand(). This function returns a random number between two numbers. Optionally, you can provide your min and max numbers as parameters, like this:
一個非常常用而且有用的函式是rand()。這函式回傳一個從0到32767之間的隨機數。有需要的話,你可以提供最小值與最大值作為參數,像這樣:



// prints a number between 0 and 32767
print rand();

// prints a number between 1 and 10
print rand(1,10);

Instructions 操作指引

- Use the editor to print a random number.
- 使用編輯器來印出隨機數。
- Create a new variable $name and store your name in it.
- 創造一個新變數$name並且將你的名字存進去。
- Then print a random character from your name. Use your knowledge of strlen(string), rand(min, max), and substr(string, start,length) to do this.
- 然後從你的名字裡頭隨機取出一個字元印出來。使用你已經學會的strlen(string),rand(min,max),和substr(string, start,length)來達成。

HINT: Remember that substr() treats characters in a string as a zero-indexed array (first letter is at position zero). This means that the last character in the string will be at position length - 1.
提示:記得substr()要傳入的要取得部分字串首字元索引值是由0開始的這代表字串的最後一個字元索引值必定為字串長度 - 1


Array Functions I 陣列函式1


Arrays are a very common thing to use in programming. In fact, array() is actually a function! Good job, you have already used an array function.
陣列是程式裡頭非常常見的東西。事實上,array()本身就是一個函式!幹得好,你已經使用了一個陣列函式。

Aside from the array() function itself, array_push() is arguably the most common and useful function for manipulating arrays.
除了array()本身,array_push()應該是最常見且有用的陣列處理函式。

array_push() takes two arguments: an array, and an element to add to the end of that array. Here's an example:
array_push()有兩個參數:一個陣列,還有一個要被加在陣列最後面的元素。這裡有一個例子:



$fav_bands = array();
array_push($fav_bands, "Maroon 5");
array_push($fav_bands, "Bruno Mars");
array_push($fav_bands, "Nickelback");
array_push($fav_bands, "Katy Perry");
array_push($fav_bands, "Macklemore");

Another cool array function is count(). Passing an array to count() will return the number of elements in that array. Like this:
另一個很酷的陣列函式是count()。傳入一個陣列到count()將會回傳該陣列的元素數量。像這樣:



print count($fav_bands); // prints 5

Instructions 操作指引

Use the editor to create an array and use array_push() to add at least 5 elements to it. Once all your elements are added, print out the number of elements in your array.
使用編輯器來創造一個陣列並使用array_push()來加入至少5個元素。當所有的元素都加上去了,印出你陣列裡頭的元素數量。


Array Functions II 陣列函式2


Another common thing to do with arrays is sort them. Handily enough, PHP has a sort()function for just such an occasion!
另一個常見的陣列動作是排序。不用自己來,PHP有一個函式sort()能夠幫你將元素裡的數字從小到大排序!


$array = array(5, 3, 7, 1);
sort($array);
print join(", ", $array);
// prints "1, 3, 5, 7"

PHP also has the opposite function: rsort().
PHP還有一個相反的函式:resort()



$array = array(5, 3, 7 ,1);
rsort($array);
print join(":", $array);
// prints "7:5:3:1"

Lastly, we use join(glue, array) so we can easily print out the representations of our sorted arrays in this exercise.
最後,我們使用join(glue, array)所以我們能夠輕易印出在本例中排序後的陣列,並在每個元素間用glue字串予以隔開。

For this exercise, we'll use a comma (,) as the glue.
在這個練習當中,我們使用逗號(,)來予以隔開


Instructions 操作指引

- On line 6, use array() to create an array with several elements and store it in $the_array.
- 在第6行,使用array()來建立一個陣列並包含數個數字元素,然後存在$the_array變數裡頭
- Next, sort() the array.
- 接著,用來為陣列的元素進行排序
- Then, print out join("," $the_array).
- 然後,印出join( “,” , $the_array )
- On line 12, rsort() the array.
- 在第12行,用 resort() 來為陣列作反向排序
- Finally, join() and print the reverse-sorted array to the screen.
- 最後,join()並print反向排序陣列到畫面上。


Show What You Know! 看看你學會了多少!


Let's take what we've learned about strings, math, and arrays and create a game. In our game, we'll make a list of our closest family and friends and have a lottery. We will "spin the wheel" and randomly select one of our family and friends from the list.
讓我們利用所學到的字串.數字和陣列函式來開發一個遊戲。在我們的遊戲裡頭,我們將親友的名字放進清單中來玩樂透。就像夜市的滾輪遊戲裡頭,隨機從清單中取出一個親友的名字。

Because winning is a big deal, we'll have to display the winner's name to the public in ALL CAPS. Let's go!
因為贏到大獎,我們必須顯示贏家的名字在畫面上,並且用大寫顯示。來吧!


Instructions 操作指引

Create an array() with the names of your closest family and friends. The more names in your array, the more fun your game will be!
array() 創造一個陣列,存放你的親友名字。在你陣列裡的名字越多,你的遊戲就越有趣!

After you've created your list, sort it and randomly select a name from the list.
在你創建你的陣列之後,sort排序它並利用rand隨機從清單中取出一個名字。

When you have your winning name, print it to the screen in caps so everyone knows how awesome the winner is.
當你取得你的贏家名字,用print將轉成大寫的贏家名字顯示在畫面上,讓每個人都知道那個幸運的玩家是誰。

Functions we'll use here: array(), array_push(), sort(), count(), rand(), and strtoupper(). Play around with some of the other functions you've learned as well.
我們需要使用array(), array_push(),sort(),count(),rand()strtoupper()這些函式。有興趣的話你也可以試用看看我們目前所學到的其他函式。

分享這篇文章:

發佈自 林品爵

林品爵
一個堅信程式教育能夠改變下一代未來的狂熱者,青少年揚帆計畫的推動者。十年以上全端程式開發,上百場程式教學經驗,累積學生數達百人以上。 成大學士畢業,使用過J2EE.PHP.MySQL.CoronaSDK.Android.Objective-C.Swift.Python等技術知識,歷任友訊科技總部Java工程師首席.黑快馬股份有限公司研發經理.諾亞數碼娛樂執行長等職位,現任哥布林程式教育學苑創辦人,所開發過專案涵括產品管理系統.POS系統.拍賣平台.擴增實境.問券.社區App等等。 程式啟蒙班講師 . Laravel網頁程式班講師 . App程式班講師

關聯文章:

留下留言