1

Array stdt contains numerical value with following structure.

Array stdt

Array
(
    [0] => 3-65
    [1] => 4-35
)

Let divide, this array as : before hyphen: first part and after hyphen: second part

Now, I want to compare this array $stdt to another variable $number.

I want to

If variable $number matches with any index's first part, then echo the number after hyphen - of matched index.

$number = '3';

$stdt = ["3-45", "4-35"];

Here, echoed value must be 45, because variable matched with first index. I am trying with following if condition, but can't conclude to expected result

if (stripos(json_encode($stdt), $number) !== false) {
    echo "index number after hyphen"; //but how to split array and echo number after hyphen
}
2

3 Answers 3

1

The initial question:

if variable $number matches with any index's first part, then echo the number after hyphen - of matched index.

To solve it, here are some less-optimized codes for you to learn from step to step:

$number = '3';
$stdt = ["3-45", "4-35"];
// loop through the array $stdt
foreach($stdt as $val) {
    // explode() is to separate the string with specific delimiter
    // in the first item in the array, $tokens[0] is 3, $tokens[1] is 45
    $tokens = explode('-', $val); 
    if($tokens[0] == $number) { // if we got a match...
        echo $tokens[1];
        break; // ...break the loop, end the process
    }
}

This code assumes you want to return 1 value only. If you want to extract all value that starts with 3-, you can remove the break; line.

From the codes in your answer, you shouldn't use json_encode(), as it's not a JSON string; also for stripos(), it is inappropriate to use in this case, as the character 3 might appear elsewhere (e.g. on the second part of the hyphenated string).

Hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Easily understanding and optimized way. +1 for detecting my mistakes. Thanks man !!!
1

Try this solution

<?php

$number = '3';
$stdt = ["3-45", "4-35"];

foreach ($stdt as $item) {
    [$index, $value] = explode('-', $item);

    if ($index === $number) {
        echo $value . "\n";
    }
}

2 Comments

This example require php 7.1 in order to use Symmetric array destructuring you can read about it in this link php.net/manual/en/…
In previous php versions you could try list($index, $value) = explode('-', $item); insted of [$index, $value] = explode('-', $item); You can read about list in this url php.net/manual/en/function.list.php
1

Simple, here you go

$number='3';

$stdt= ["3-45", "4-35"];

array_map(function($item)use($number){if(0===strpos($item,$number.'-'))echo substr($item,strlen($number.'-'))."\n";},$stdt);

Output

45

Sandbox

UPDATE1

I thought about "golfing" it ... ha ha (97 bytes 92 without the newline).

$n='3';

$a= ["3-45", "4-35"];

array_map(function($i)use($n){$n.='-';echo 0===strpos($i,$n)?substr($i,strlen($n))."\n":'';},$a);

Smallifed Version

It even correctly accounts for things like

$number = 3;
//where 33 could be matched by "false !== strpos($i,$n)"
$stdt= ["3-45", "4-35", "33-99"];

I will explain the smallified version as its more complex.

  1. array_map walks though an array and applies a callback function, you can think of it like a loop.
    • in this case its a user supplied closure, with the input if $i
    • we need the number $n in so we pass it in by using use($n)
  2. foreach loop, we append the - to the number. $n=3 becomes $n='3-'
    • this just shortens things for us latter on
  3. we use a shorthand "ternary" if statement it takes the from of
    • condition ? if true : if false;
    • strpos - check the position of one string in another and returns it
    • in this case we want to check if $n='3-' is 0 or the first position (0 based index)
    • by adding the - to the number we can be sure it doesn't match things like $i='33-'. For example 3- does not match 33- but 3 can.
    • we use === strict type checking because strpos returns boolean false if it's not in the string and false == 0 is true, but false === 0 is not because they are different types.
  4. [IF TRUE] then we basically remove $n from $i.
    • we can use the length of $n which is $n='3-' or 2 to get the start position for sub string. So we could write it like substr('3-45', 2) but because $n can be anything, it's better to measure it
  5. [IF false] we just return an empty string which gets returned to echo.

Expanded Version Of Code:

 array_map(
     function( $i ) use ( $n ){
         $n .= '-';
         echo (0 === strpos( $i, $n ) ) ? substr( $i, strlen( $n ) ) : '';
     },
 $a);

Difference between 1 & 2

The first version is basically the same, but I realized I could shorten it by adding the - on to the number before hand instead of appending it twice.

The major differences are

  • shortened the variables to 1 letter (just to save space)
  • Using ternary instead of a normal if statement

UPDATE2

Last thing I will do is write a Bigger more normal looking version:

$number = 3;
$stdt= ["3-45", "4-35", "33-99", '3-33'];

//makes life easier, also solves some issues by converting number to a string.
//We set it outside the loop for performance, we could add it with . every time but that's just waste.
$n = $number .'-';
//length of n
$l = strlen($n);
foreach($stdt AS $st){
    //find the position of $n, 0 = first, false = not found
    //again === strict type chcking
    if(0 === ($pos = strpos($st, $n))){
        //use the length of $n (one of those makes life easier things)
        //here we can use substr its much safer then trim.
        echo substr($st, $l))."\n";
    }

}

Bigified Version

There is probably a million ways you can do this. I did the above because it gets boring so it's fun to try to make it as small and short as possible.

Cheers!

:-p - thanks for the fun!

PS I got rid of the one with trim, it's to problematic and hard to explain when they remove stuff in different ways. Now they are are roughly equivalent.

4 Comments

I think you might want to explain your code to OP, as OP seems a little bit inexperienced in PHP. Also, the one-liner code is hard to read, though it can give the expected output.
@ArtisticPhoenix Highly appreciated your explanation, becomes easy to get more knowledge
Sure, I get bored with plain old foreach there is actually a stack exchange section called "Code Golf" that is basically a game to write the smallest program possible. It's actually kind of hard with PHP, although I've done a few interesting ones on there.
Code Golf, hadn't idea about the topic, recently read and visit about this, shortest->+1. Really worthy to follow, once again Thanks man ! for new information !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.