Mark
Mark

Reputation: 121

Need Help in building a logic

I need to get all the positions of a character in a string in a form of an array. I know about the php function strpos() but it does not accept an array as an argument.

This is required:

$name = "australia";            //string that needs to be searched
$positions_to_find_for = "a";   // Find all positions of character "a" in an array 
$positions_array = [0,5,8];     // This should be the output that says character "a" comes at positions 0, 5 and 8 in string "australia"

Question: What Loops can help me build a function that can help me achieve the required output?

Upvotes: 0

Views: 66

Answers (2)

Mihai Iorga
Mihai Iorga

Reputation: 39704

You can use a for to loop that string:

$name = "australia";
$container = array();
$search = 'a';
for($i=0; $i<strlen($name); $i++){
    if($name[$i] == $search) $container[] = $i;
}

print_r($container);

/*
Array
(
    [0] => 0
    [1] => 5
    [2] => 8
)
*/

Codepad Example

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

No loops necessary

$str = 'australia';
$letter='a';
$letterPositions = array_keys(
    array_intersect(
        str_split($str),
        array($letter)
    )
);

var_dump($letterPositions);

Upvotes: 1

Related Questions