altgetMiddle()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
4
5
// Examples:
6
7
Kata.getMiddle("test") should return "es"
8
9
Kata.getMiddle("testing") should return "t"
10
11
Kata.getMiddle("middle") should return "dd"
12
13
Kata.getMiddle("A") should return "A"
14
15
// Input
16
17
A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.
18
19
// Output
20
21
The middle character(s) of the word represented as a string.
22
*/
23
24
function getMiddle($text)
25
{
26
    $returnedText = "";
27
    $length = strlen($text);
28
    $middle = $length / 2;
29
30
    if ($length % 2 == 0) {
31
        $returnedText = $text[$middle-1];
32
        $returnedText.= $text[$middle];
33
    }
34
    $returnedText.= $text[$middle];
35
    return $returnedText;
36
}
37
38
// Alternative method:
39
40
function altgetMiddle($text)
41
{
42
    $len = strlen($text);
43
    if ($len % 2 === 0) {
44
        return substr($text, $len / 2 - 1, 2);
45
    }
46
    return substr($text, $len / 2, 1);
47
}
48