Last active
August 29, 2015 14:06
-
-
Save ajschlosser/d19ef640b5fa7d3814b2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_halves ($a) { | |
$total_length = 0; | |
for($i = 1; $i <= count($a); $i++) { | |
$total_length += strlen($a[$i]); | |
} | |
echo "Cutting an array of ".count($a)." strings totaling ".$total_length." characters in half:<br><br>"; | |
$first_half_length = 0; | |
$second_half_length = 0; | |
$second_half_index = 0; | |
$done = false; | |
for($i = 1; $i <= count($a); $i++) { | |
if (!$done) { | |
$first_half_length += strlen($a[$i]); | |
echo "Begin iteration. The length of the first half is now ".$first_half_length."<br>"; | |
if ($first_half_length < ceil($total_length/2)) { | |
echo "[".$i."]: ".$a[$i]." (Continuing, because ".$first_half_length." is less than ".ceil($total_length/2).")<br>"; | |
} | |
else { | |
echo "[".$i."]: ".$a[$i]." (This is the last string in the first half.)<br>"; | |
$done = true; | |
$second_half_index = $i + 1; | |
$second_half_length = $total_length - $first_half_length; | |
echo "Stopping at [".$i."], because ".$first_half_length." is larger than or equal to ".ceil($total_length/2)."<br>"; | |
} | |
$msg = "No."; | |
if ($done) $msg = "Yes."; | |
echo "End iteration. Are we done? ".$msg."<br>"; | |
} | |
} | |
echo "--- IDENTIFY HALF AT INDEX: (".$second_half_index.") ---<br>"; | |
if ($second_half_index > 0) { | |
for($i = $second_half_index; $i <= count($a); $i++) { | |
echo "[".$i."]: ".$a[$i]."<br>"; | |
} | |
} else { | |
echo "There was a problem."; | |
} | |
echo "<br><br>Total length: ".$total_length."<br>"; | |
echo "First half length: ".$first_half_length."<br>"; | |
echo "Second half length: ".$second_half_length."<br>"; | |
} | |
$a = array( | |
1=>"one two buckle my shoe", | |
2=>"two", | |
3=>"three", | |
4=>"four", | |
5=>"five (5)" | |
); | |
get_halves($a); | |
$a = array ( | |
1=>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", | |
2=>"Lorem ipsum dolor sit amet.", | |
3=>"Lorem ipsum.", | |
4=>"Lorem ipsum dolor." | |
); | |
get_halves($a); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment