user3515469
user3515469

Reputation:

Position of an element in an array with Starting Character of the element

I Wan to find a positions of an element using the starting character of the element. the example as follow

array(
   0=>"1-2",
   1=>"2-3"
   2=>"3-4"
   3=>"4-3"
)

This is my array. in This array i want find the positions of element starting with 2-, How can i find with PHP, can any one help.

Upvotes: 0

Views: 144

Answers (5)

Phylogenesis
Phylogenesis

Reputation: 7880

A more general approach is:

$input = array('1-2', '2-3', '3-4', '4-3');
$search = '2-';

$results = array_filter(
    $input,
    function ($item) use ($search) {
        return strpos($item, $search) === 0;
    }
);

// $results will contain an array of all strings that match.

Upvotes: 0

Mohammed Al Ashaal
Mohammed Al Ashaal

Reputation: 422

$input = array('1-2', '2-3', '3-4', '4-3');
$search = '2-';
var_dump(preg_grep("/^{$search}/", $input));

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

$needle = '2-';
$result = array_filter(
    $myArray,
    function($value) use ($needle) {
        return fnmatch($needle.'*', $value);
    }
);
var_dump($result);

Upvotes: 0

hsz
hsz

Reputation: 152206

Just try with:

$input = array(
    0 => "1-2",
    1 => "2-3",
    2 => "3-4",
    3 => "4-3",
);

$search = '2-';

$index = -1;
foreach ($input as $key => $value) {
    if (strpos($value, $search) === 0) {
        $index = $key;
        break;
    }
}

Upvotes: 1

Samuel Cook
Samuel Cook

Reputation: 16828

This would be my approach if you want to find a string starting with particular characters:

<?php
$find = '2-';
$array = array(0=>"1-2", 1=>"2-3", 2=>"3-4", 3=>"4-3");
$position = NULL;

foreach($array as $key=>$val){
    if( substr($val,0,strlen($find)) == $find ){
        $position = $key;
        break;
    }
}

echo $position;

I used strlen in the substr() to allow for any string of characters.

Upvotes: 1

Related Questions