How to push a value based on matched value in PHP ?


To push a value based on a matched value in PHP, you can use the array_search() function to find the index of the matched value and then use the array_splice() function to insert the new value at the appropriate index.

Here's an example:

$fruits = array('apple', 'banana', 'orange', 'grape');

// Find the index of the matched value
$index = array_search('orange', $fruits);

// Insert the new value at the appropriate index
array_splice($fruits, $index+1, 0, 'pear');

print_r($fruits);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => pear
    [4] => grape
)

In this example, we have an array of fruits and we want to insert the value 'pear' after the value 'orange'. We use array_search() to find the index of 'orange' and then use array_splice() to insert 'pear' at the index after 'orange'.

Another way to achieve the same result is by using a foreach loop to iterate over the array and check for the matched value. Once the matched value is found, we can use the array_splice() function to insert the new value at the appropriate index.

Here's an example:

$fruits = array('apple', 'banana', 'orange', 'grape');
$new_fruit = 'pear';

foreach ($fruits as $key => $value) {
    if ($value == 'orange') {
        array_splice($fruits, $key+1, 0, $new_fruit);
        break;
    }
}

print_r($fruits);

Output:

Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => pear
    [4] => grape
)

In this example, we use a foreach loop to iterate over the array and check for the matched value 'orange'. Once the value is found, we use array_splice() to insert the new value 'pear' at the index after 'orange'. We also use the break statement to exit the loop once the value is found, as we don't need to continue iterating over the array.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.