php - Rebuild array with standard keys

Solution:
if (condition) {
array_shift($pieces);
}
print_r($pieces);
Answer
Solution:
Or you can use array_values to reset all the keys.
if (condition) {
unset($pieces[0]);
$pieces = array_values($pieces);
}
If you remove item [5], it will make [6] -> [5]
Answer
Solution:
You can use the PHP array_shift() function to remove the first element or value from an array. The array_shift() function also returns the removed value of array. However, if the array is empty (or the variable is not an array), the returned value will be NULL.
<?php
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
// Deleting first array item
$removed = array_shift($pieces);
print_r($pieces);
echo "<br>";
var_dump($removed);
?>
Output
Array ( [0] => piece2 [1] => piece3 [2] => piece4 [3] => piece5 [4] => piece6 )
// Removed
string(6) "piece1"
Answer
Solution:
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$arr = explode(" ", $pizza);
foreach($arr as $k => $v) {
if($v == 'piece3' || $v == 'piece5') {
array_splice($arr, $k, 1);
}
}
print_r($arr);
// Array
// (
// [0] => piece1
// [1] => piece2
// [2] => piece4
// [3] => piece5
// )
Answer
Solution:
Have a look at the array_filter function. It makes you able to use even more complex decisions.
$result = array_filter($pieces, function($index) {
return $index > 0;
}, ARRAY_FILTER_USE_KEY);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: malformed utf-8 characters, possibly incorrectly encoded
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.