<?php
$colors = ["Red", 7735, "Blue"];
$colors[] = "Yellow"; //add new member in last position
echo $colors[0];
echo "\n\n\n";
print_r($colors);
echo "\n\n\n";
var_dump($colors);
OUTPUT:
Red
Array
(
[0] => Red
[1] => 7735
[2] => Blue
[3] => Yellow
)
array(4) {
[0]=>
string(3) "Red"
[1]=>
int(7735)
[2]=>
string(4) "Blue"
[3]=>
string(6) "Yellow"
}
function majorityElement($nums) {
$quantity = count($nums);
$nums = array_count_values($nums);
foreach($nums as $key => $num) {
// two values can't be more than 50% of array
if ($num > $quantity / 2) {
return $key;
}
}
}
echo majorityElement([0, 1, 1, 3, 4, 1, 1]); //1
echo majorityElement([2, 2 ,1 ,1 ,1 ,2 ,2]); //2
function searchInsert($nums, $target) {
if (in_array($target, $nums)) {
$index = array_search($target, $nums);
return $index;
}
if (!in_array($target, $nums)) {
array_push($nums, $target);
sort($nums);
$index2 = array_search($target, $nums);
return $index2;
}
}
echo searchInsert([1, 3, 5, 6], 5); // 2
echo searchInsert([1, 3, 5, 6], 2); // 1
function containsDuplicate($nums) {
$nums = array_count_values($nums);
foreach ($nums as $key => $num) {
if ($num >= 2) {
return true;
}
}
return false;
}
echo containsDuplicate([1, 2, 3, 1]);