Home > Software engineering >  Check if a word is inside one of the elements of an associative array in php
Check if a word is inside one of the elements of an associative array in php

Time:06-22

Currently I have the following array that checks if all the text of one of the elements of an array exists and gets its position.

In this example if the word is "Delivered at pack point" it will get position 3. :

$word = 'Delivered at pack point';

$states = array(
    1 => 'Picked up at agency',
    2 => 'In delivery',
    3 => 'Delivered at pack point'
);
$position_ini = array($word);
$ar_inter = array_intersect($states, $position_ini); 
$position = $key($ar_inter);
echo $position;// 3

But it can happen that the initial word is just a string, for example "Delivered" or "Delivered to a third party".

So how do I get it to get to position 3 if the initially arriving word contains the text of "Delivered" and is inside one of the array elements, to get its position?

CodePudding user response:

I believe you will have to loop through the array and compare each string, like below

<?php 
$word = 'Delivered at pack point';

$states = array(
    1 => 'Picked up at agency',
    2 => 'In delivery',
    3 => 'Delivered at pack point'
);

for($i=1; $i<=count($states); $i  ){
    if(strpos($states[$i],$word) !== FALSE){
        echo $i;
        break;
    }
}

?>

I hope that helps.

CodePudding user response:

Or simply with array_key_first, array_filter and str_contains. Returns empty if false, first key if true. Case sensitive.

$word = 'Delivered';

$states = array(
    1 => 'Picked up at agency',
    2 => 'In delivery',
    3 => 'Delivered at pack point'
);

echo array_key_first(array_filter($states, fn($var) => str_contains($var, $word)));

Results 3

  • Related