Jump to content

in_array modification


knowram

Recommended Posts

I was not able to make that work. Really I think I am just looking for a way to see if a variable starts with specific letters.here is an example of what i am trying to do.

given $array1 = array('med:1','med:2','med:3','temp','start');

I would like to write a for loop something like this

[code]
for ($i = "0"; $i <= "4"; $i++){
  if ($arra1[$i] starts with "med:"){ //do something}
  else{ // do something different}
}
[/code]
Link to comment
Share on other sites

Try something like this:

[code]
<?php
  $array1 = array('med:1','med:2','med:3','temp','start');

  foreach ($array1 AS $val) {
    if (preg_match('/^(med\:)/',$val)) {
      //do something here
    }
    else {
      //do something else here
    }
   
  }
?>

[/code]
Link to comment
Share on other sites

I would do it like this:

[code]
<?php
/**
* @author: Nick Stinemates // keeb
* @description: Searches array for keys beginning with certain char's
*/

  $array1 = array('med:1','med:2','med:3','temp','start');

  foreach ($array1 AS $val) {
switch ($val) {
case strpos($val, "med:"):
//do something
break;
default:
//do something else
}
   
  }
?>
[/code]
Link to comment
Share on other sites

The heck? Why are you using a switch when there's only two possibilities? Also, your code will trigger a false positive if the substring is somewhere in the string besides the first four letters.

[code]<?php

$array1 = array('med:1','med:2','med:3','temp','start');

foreach($array1 as $item){
if(strpos($item,"med:")===0){
//Note we used === instead of ==. false==0, but false!==0.
//Also note that using strpos instead of regular expressions is faster for simple searches like this.
//Do something
}
else{
//Do something else
}
}
?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.